0Pricing
Android Academy · Lesson

Memory Leaks and Fixes

Find and stop leaks.

What Is a Memory Leak?

A memory leak happens when objects that are no longer needed cannot be garbage collected because something still holds a reference to them. On Android the classic victim is an Activity or Context that lingers after its screen is destroyed.

Leaks grow your heap over time, trigger more frequent garbage collection (which pauses the UI and causes jank), and eventually crash the app with an OutOfMemoryError. This lesson shows how to find and fix them.

How GC Decides What to Keep

Android's garbage collector keeps any object that is reachable from a GC root (live threads, static fields, etc.). Anything unreachable is freed.

A leak is simply an unwanted reachability path: a long-lived object holding a reference to a short-lived one. The pure-Kotlin demo below shows reachability keeping an object alive.

object GlobalCache {
    val items = mutableListOf<ByteArray>()
}

fun cacheSomething() {
    // This 1MB array stays alive forever because GlobalCache
    // (a static singleton, a GC root) keeps referencing it.
    GlobalCache.items.add(ByteArray(1_000_000))
}

fun main() {
    repeat(3) { cacheSomething() }
    println("Held arrays: ${GlobalCache.items.size}") // never freed
}

All lessons in this course

  1. Measuring Performance
  2. Taming Recomposition
  3. Memory Leaks and Fixes
  4. Startup and Baseline Profiles
← Back to Android Academy