skip to content

How does LeakCanary tell a Library Leak from an Application Leak, and what do you do when a third-party SDK keeps leaking your activity?

level: seniorimportance: should knowfreq 30%

answer

  1. a database of known leaks
  2. pattern match on reference names
  3. LibraryLeakReferenceMatcher vs IgnoredReferenceMatcher
  4. report upstream, then add a matcher

basics

~20 s

LeakCanary matches each trace against known leak patterns, AndroidReferenceMatchers by default; a leak whose only path runs through a matched reference is a Library Leak. For a leaking SDK, report it upstream and add your own matcher meanwhile.

solid answer

~50 s

LeakCanary ships a database of known leaks in Android and manufacturer code, `AndroidReferenceMatchers`, and matches leak traces against those reference patterns. Each pattern is a `LibraryLeakReferenceMatcher`; Shark's shortest-path search only walks through matching references after it has exhausted all others, so a path free of known patterns always wins. If the only path to the object goes through a known pattern, the result is reported under **Library Leaks**, with the pattern's description. You cannot skip the heap dump for it: LeakCanary only knows after analysis. For a third-party SDK that keeps leaking, I'd confirm the cause is in its code, file or find the bug report, and meanwhile add a matcher via `LeakCanary.config.copy(referenceMatchers = AndroidReferenceMatchers.appDefaults + AndroidReferenceMatchers.instanceFieldLeak(...))`. If the SDK's own activity or fragment leaks, I can also filter it out with a custom `ReachabilityWatcher`.

code

kotlin · 17 lines
kotlin
import leakcanary.LeakCanary
import shark.AndroidReferenceMatchers

// NewsApplication is the app's open Application subclass in src/main.
class DebugNewsApplication : NewsApplication() {
    override fun onCreate() {
        super.onCreate()
        LeakCanary.config = LeakCanary.config.copy(
            referenceMatchers = AndroidReferenceMatchers.appDefaults +
                AndroidReferenceMatchers.instanceFieldLeak(
                    className = "com.vendor.sdk.SessionManager",
                    fieldName = "hostActivity",
                    description = "Vendor SDK keeps the last host activity; reported upstream."
                )
        )
    }
}

go deeper

for a junior

Know that LeakCanary shows two groups, Application Leaks and Library Leaks, and that a Library Leak comes from a known bug in code you do not own.

for a middle

Explain the known-pattern database, AndroidReferenceMatchers, and that the split happens during heap analysis, not before the dump.

for a senior

Describe how Shark prefers non-matching references, the difference between library-leak and ignored matchers, and the full playbook for a leaking vendor SDK.

for a principal

Treat every custom matcher as tracked debt with an upstream bug link and an owner, and review the list when the SDK updates so fixed leaks are not masked.

## Two kinds of leak LeakCanary sorts every leak it finds into one of two categories: | | Application Leak | Library Leak | |---|---|---| | Cause | a reference your code failed to clear | a known bug in code you do not control | | Recognized by | no known pattern on the path | a known pattern on the only path found | | Shown as | the application leaks section of the result | a separate library leak section, `Library Leak` badge | | Fails a UI test with the default reporter | yes | no, logged only | A **Library Leak** is still a real leak: memory is still wasted and the activity is still kept. LeakCanary separates it because the fix is usually not in your hands. ## How the match works LeakCanary's analysis library, **Shark**, receives a list of **reference matchers** from `LeakCanary.config.referenceMatchers`, which defaults to `AndroidReferenceMatchers.appDefaults`, a large catalogue of leaks found over the years in AOSP and in manufacturer builds. Each entry describes a reference pattern, such as a static field, an instance field or a native global variable of a named class, plus a description and an optional `patternApplies` condition on the device (for example manufacturer and SDK level). There are two kinds of matcher: - **`LibraryLeakReferenceMatcher`**: the shortest path finder only goes through matching references after it has exhausted references that don't match. If it still reaches the retained object, the leak is reported as a Library Leak with the pattern and description printed above the trace. - **`IgnoredReferenceMatcher`**: the path finder never goes through a matching reference at all. Use it for references that cannot create leaks. The ordering matters: if your code also holds the object through a path with no known pattern, Shark finds that path first and you get an Application Leak, so a library pattern cannot hide a separate bug of yours that holds the same object. LeakCanary cannot know a leak is a Library Leak before it has dumped and analyzed the heap, so there is no switch to skip the dump for library leaks; it reports them so you are not left wondering what happened after the dump. ## What to do when an SDK keeps leaking your activity 1. **Confirm the cause is theirs.** Read the suspect references: the underlined field should belong to the SDK's classes, not to a callback you registered and forgot. 2. **Check whether it is already known.** A recognized pattern appears as a Library Leak with a description; an unrecognized one shows up as an Application Leak whose suspects sit in SDK code. 3. **Push for a fix.** Find or file the bug with the vendor, including the full trace and metadata; for an Android framework leak, the project asks for an issue and a pull request adding the pattern. 4. **Teach LeakCanary the pattern meanwhile**, so the team stops re-triaging it: ```kotlin LeakCanary.config = LeakCanary.config.copy( referenceMatchers = AndroidReferenceMatchers.appDefaults + AndroidReferenceMatchers.instanceFieldLeak( className = "com.vendor.sdk.SessionManager", fieldName = "hostActivity", description = "Vendor SDK keeps the last host activity until the next session." ) ) ``` 5. **If the leaking object is the SDK's own activity or fragment**, you can stop watching just those instances: disable the automatic install with the `leak_canary_watcher_auto_install` resource, then call `AppWatcher.manualInstall()` with `AppWatcher.appDefaultWatchers(application, ReachabilityWatcher { watchedObject, description -> ... })` that skips that class and forwards everything else to `AppWatcher.objectWatcher.expectWeaklyReachable()`. ## Workarounds and their limits - Some library leaks can be cleared with reflection or by exercising a code path that releases the reference. These fixes are fragile and break on the next SDK update. - Marking a leak as a library leak does not free memory; on a memory-tight screen it may still matter for low-memory kills. - A matcher with a broad pattern, such as a common field name, can relabel genuine application leaks if no other path exists; keep patterns specific to the vendor's class and field. ## Why this matters in tests The default reporter behind `LeakAssertions.assertNoLeaks()` throws only for Application Leaks and logs Library Leaks. Adding a precise matcher therefore keeps an unfixable vendor leak from failing every UI test, while new application leaks still fail the tests that check for them.

  • Could a broad library-leak matcher hide a leak in your own code?
    Only partly. Shark explores non-matching references first, so if your code holds the object through any path without a known pattern, that path wins and the leak stays an Application Leak. A matcher only relabels leaks whose sole path runs through the matched reference. A pattern that is too broad, such as a generic field name, can still swallow a real bug on that path, so keep matchers specific.
  • When would you use an IgnoredReferenceMatcher instead of a library-leak matcher?
    When a reference genuinely cannot keep an object alive longer than intended, so it should never appear in a path. Shark never traverses an ignored reference, which can expose the real path behind it. A library-leak matcher is for references that do leak but that you cannot fix, so they are still reported, just in the separate Library Leaks section.

  • Library Leaks are false positives that can be ignored
  • LeakCanary can skip the heap dump when it knows a leak is a library leak
  • Any leak through a third-party class is automatically a Library Leak
  • A library-leak matcher hides every leak of that activity, including mine
  • Library Leaks fail instrumentation tests just like application leaks by default