skip to content

After rotating a screen several times, LeakCanary reports a leaked activity; how do you read its leak trace to find the reference to fix?

level: middleimportance: must knowfreq 55%

answer

  1. read top to bottom
  2. GC root, then the reference chain
  3. Leaking: NO, UNKNOWN, YES
  4. the ~~~ underlines narrow it

basics

~20 s

Read the leak trace from the GC root down to the destroyed activity. Objects are marked Leaking: NO, UNKNOWN or YES; the underlined suspects lie between the last NO and the first YES, and the one never cleared is the bug.

solid answer

~50 s

A leak trace is the best strong reference path from a GC root to the retained object. The first line names the **GC root**, such as `System class`; each `├─` line is an object, each `↓` line the field or array slot pointing to the next object, and `╰→` is the watched object. Under each object LeakCanary prints `Leaking: NO`, `UNKNOWN` or `YES` with a reason, for example "a class is never leaking" or "Activity#mDestroyed is true". Only references between the last `NO` and the first `YES` can be the cause, so it underlines those with `~~~`. In the rotation case I'd expect a chain like singleton, `listeners` list, `ArrayList.elementData`, destroyed activity: the list internals are implementation details, so the bug is the activity staying in the singleton's `listeners` after `onDestroy()`. The fix is to unregister in the matching teardown callback, not to switch to a weak reference.

code

kotlin · 23 lines
kotlin
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class ArticleActivity : AppCompatActivity(), SessionTracker.Listener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SessionTracker.listeners += this
    }

    override fun onDestroy() {
        // The missing line behind the leak trace: drop the reference
        // that SessionTracker.listeners would otherwise keep forever.
        SessionTracker.listeners -= this
        super.onDestroy()
    }

    override fun onSessionChanged() { /* update UI */ }
}

object SessionTracker {
    interface Listener { fun onSessionChanged() }
    val listeners = mutableListOf<Listener>()
}

go deeper

for a junior

Know that the trace runs from a GC root down to the leaked object, and that the cause is a reference somebody forgot to clear, such as a listener never unregistered.

for a middle

Read the notation fluently: root type, object lines, reference lines, the Leaking verdicts and the ~~~ suspects between the last NO and first YES.

for a senior

Reason from the suspects to the missing teardown, rule out library internals, add inspectors such as AppSingletonInspector to sharpen traces, and reject the weak-reference shortcut with the reason.

for a principal

Use signatures as the unit of work: one ticket per signature, new signatures triaged first, so a team spends effort on distinct bugs rather than on instance counts.

## What a leak trace is When LeakCanary analyzes a heap dump, it looks for each **retained object** (an object it was watching that is still in memory) and computes its **leak trace**: the best strong reference path from a **garbage collection root** to that object. A **GC root** is something the runtime always treats as reachable, such as a loaded class, a running thread or a reference held by native code. As long as any path of strong references connects a root to the object, the collector cannot reclaim it. Somewhere on that path is a reference that should have been cleared and was not; finding it is the whole job. ## Reading the notation Take a news app whose `ArticleActivity` registers itself with an app-wide `SessionTracker` singleton in `onCreate()` and never unregisters. After a few rotations LeakCanary reports: ```plaintext ┬─── │ GC Root: System class │ ├─ com.example.news.SessionTracker class │ Leaking: NO (a class is never leaking) │ ↓ static SessionTracker.listeners │ ~~~~~~~~~ ├─ java.util.ArrayList instance │ Leaking: UNKNOWN │ ↓ ArrayList.elementData │ ~~~~~~~~~~~ ├─ java.lang.Object[] array │ Leaking: UNKNOWN │ ↓ Object[].[3] │ ~~~ ╰→ com.example.news.ArticleActivity instance Leaking: YES (ObjectWatcher was watching this because com.example.news.ArticleActivity received Activity#onDestroy() callback and Activity#mDestroyed is true) ``` Read it line by line: - `┬───` opens the trace, and `GC Root: System class` names the root type. Other common values are `Local variable in native code`, `Global variable in native code`, `Java local variable` and `Thread object`. - `├─` lines are objects: a class, an instance or an array. - `│ ↓` lines are references: a static field (`static SessionTracker.listeners`), an instance field (`ArrayList.elementData`) or an array slot (`Object[].[3]`) leading to the next object. - `╰→` is the retained object itself, the one handed to the object watcher. - `Leaking:` gives LeakCanary's verdict on each object, with the reason in parentheses. In words: the `SessionTracker` class (a Kotlin `object`, whose properties compile to static fields) holds a `listeners` field; that field holds an `ArrayList`; the list's backing array holds, at index 3, a destroyed `ArticleActivity`. ## How LeakCanary narrows the suspects Initially every reference in the path is a suspect. LeakCanary then applies **object inspectors** (`AndroidObjectInspectors.appDefaults`) that know Android lifecycles: 1. A class is never leaking, and the `Application` is a singleton, so both get `Leaking: NO`. 2. An `Activity` whose `mDestroyed` field is `true`, or a `View` whose context is a destroyed activity, gets `Leaking: YES`. 3. Objects it cannot judge stay `Leaking: UNKNOWN`. 4. A reference *into* a `NO` object cannot be the bug (that object is supposed to be alive), and a reference *out of* a `YES` object cannot be the bug either (that object should already be gone). So only references between the last `NO` and the first `YES` stay underlined with `~~~`, shown in red in the app's UI. You can help the narrowing with your own inspectors. When an app-wide singleton instance shows up mid-trace as `Leaking: UNKNOWN`, adding `AppSingletonInspector("com.example.news.SessionTracker")` to `LeakCanary.config.objectInspectors` marks it `Leaking: NO`, which removes the reference into it from the suspects. ## Finding the reference to fix With the suspects narrowed, reason about each one: - `ArrayList.elementData` and `Object[].[3]` are internals of the standard list; a bug there is very unlikely. - That leaves `static SessionTracker.listeners`: the activity was added and never removed. Then ask when that reference should have been cleared. Registration in `onCreate()` pairs with removal in `onDestroy()`; registration in `onStart()` pairs with `onStop()`. Every rotation creates a new instance that registers again, so without removal the list keeps every old instance. The fix is to unregister in the matching callback, or to give the listener a lifecycle-aware owner that unregisters itself. The project documentation is explicit about the tempting shortcut: replacing the strong reference with a `WeakReference` does not fix a leak. The stale registration is still there, objects may now disappear earlier than intended, and the code becomes harder to reason about. ## Grouping and signatures Five rotations produce five retained activities, but LeakCanary shows them as **one** leak. It computes a **leak signature**, a hash of the concatenated suspect references, and groups traces with the same signature because they share one bug. A row is badged `New` the first time a signature appears. Leaks are also split into **Application Leaks** (yours) and **Library Leaks** (known bugs in Android or third-party code). ## When the trace is not enough - Add labels with a custom `ObjectInspector` to print state, such as an entity id, under an object. - Share the heap dump from the analysis screen and open it in a desktop heap analyzer; the retained object is the `referent` of the `leakcanary.KeyedWeakReference` whose `key` matches the one LeakCanary reported. - Check the `Retaining ... in ... objects` line, shown when retained heap size is computed, to see how much memory the leak holds.

  • Why does LeakCanary underline only some references instead of the whole path?
    Object inspectors classify each object. A reference into an object marked `Leaking: NO` cannot be the bug, because that object is meant to be alive, and a reference out of an object marked `Leaking: YES` cannot be either, because that object should already be gone. Only references between the last `NO` and the first `YES` remain suspects, and those are the ones underlined with `~~~`.
  • Why are five leaked instances from five rotations shown as a single leak?
    LeakCanary computes a leak signature by hashing the concatenated suspect references, then groups traces with the same signature. All five instances are held by the same `SessionTracker.listeners` path, so they share a signature and one fix removes all of them. Two different bugs leaking the same activity class would get two signatures and two rows.
  • What does the GC root type at the top of the trace tell you?
    It tells you what anchors the chain. `System class` means a loaded class, typically reached through a static field; `Thread object` or `Java local variable` points at a running thread or a stack frame, such as a background task still holding a callback; native-code roots often belong to the runtime itself, such as a class loader in front of your own static field. The root rarely names the bug; the suspect references do.

  • The GC root at the top is the reference you need to remove
  • Every reference in the trace is equally likely to be the cause
  • Wrapping the activity in a WeakReference fixes the leak
  • Five leaked instances mean five different bugs to fix
  • Leaking: UNKNOWN means LeakCanary failed to analyze that object