What does LeakCanary 2 watch automatically, when does a watched object count as retained, and when does it dump the heap?
answer
- four default watchers
- weak reference plus a delay
- 5 seconds, then a forced GC
- 5 while visible, 1 in background
basics
~20 sLeakCanary 2 watches destroyed activities, fragments, fragment views and services, cleared ViewModels and detached root views. One still reachable 5 seconds later, after a GC, is retained; it dumps the heap at 5 retained while visible, 1 in the background.
solid answer
~40 sSince LeakCanary 2.6, `AppWatcher` installs four default watchers: `ActivityWatcher` (activities after `onDestroy()`), `FragmentAndViewModelWatcher` (fragments after `onDestroy()`, their views after `onDestroyView()`, ViewModels after `onCleared()`), `RootViewWatcher` (root views such as toasts once detached) and `ServiceWatcher` (services after `onDestroy()`). Each hands the object to `AppWatcher.objectWatcher.expectWeaklyReachable()`, which holds it through a weak reference. If that reference is not cleared after `retainedDelayMillis` (5 seconds by default), the object is **retained**; LeakCanary forces a GC and recounts. It does not dump yet: while the app is visible it waits for `retainedVisibleThreshold` (default 5) retained objects, because a dump freezes the UI. Once the app has been in the background for the watch delay, a single retained object is enough. Tapping the notification dumps immediately; dumps are at least 60 seconds apart and held back while a debugger is attached.
go deeper
Name what is watched by default: destroyed activities and fragments, and cleared ViewModels. Say an object is flagged when it is still in memory a few seconds after it should be gone.
Walk through expectWeaklyReachable, the weak reference, the 5-second delay and the forced GC, then the threshold of 5 while visible and 1 in the background.
Explain why the batching exists, why a debugger blocks dumps, why fragment views are watched separately, and how manualInstall with a filtered watcher list changes the default set.
Weigh the threshold as a team setting: lower values catch leaks sooner but interrupt every developer more often; most teams keep the default and back it with leak checks in tests.
## The pipeline in one sentence LeakCanary 2 works in four steps: it **detects retained objects**, **dumps the heap**, **analyzes the heap** with its Shark library, and **categorizes the leaks** it finds. This question is about the first two steps: what gets watched, when an object is declared retained, and what decides the moment of the heap dump. ## What is watched automatically `AppWatcher` is the object that owns detection. On startup it installs a list of **watchers** built by `AppWatcher.appDefaultWatchers(application)`; since LeakCanary 2.6 that list is: | Watcher | Object handed over | Moment | |---|---|---| | `ActivityWatcher` | the `Activity` | after `onDestroy()` | | `FragmentAndViewModelWatcher` | the `Fragment` | after `onDestroy()` | | `FragmentAndViewModelWatcher` | the fragment's root `View` | after `onDestroyView()` | | `FragmentAndViewModelWatcher` | each `ViewModel` | after `onCleared()` | | `RootViewWatcher` | a window's root view | after it is detached from the window manager | | `ServiceWatcher` | the `Service` | after `onDestroy()` | A few details matter in practice: - `RootViewWatcher` skips activity windows (the activity watcher covers them) and popup windows; it watches toasts, tooltips and other windows. Dismissed dialogs are watched only when the `leak_canary_watcher_watch_dismissed_dialogs` resource is set to `true`, which is off by default. - A fragment's view is watched separately from the fragment because a fragment on the back stack outlives its view; holding the view after `onDestroyView()` is a classic leak. - The older `AppWatcher.config` flags such as `watchActivities` are deprecated; the current way to change the set is `AppWatcher.manualInstall()` with a filtered `watchersToInstall` list. ## When an object counts as retained Every watcher calls `expectWeaklyReachable(watchedObject, description)` on `AppWatcher.objectWatcher`, an `ObjectWatcher`. 1. The watcher wraps the object in a `KeyedWeakReference` with a random key and the description, for example "received Activity#onDestroy() callback". 2. A check is scheduled `retainedDelayMillis` later, 5 seconds by default. 3. A **weak reference** is cleared by the garbage collector once nothing else strongly references the object. If the reference has been cleared by the time the check runs, the object was collected and is forgotten. 4. If it has not been cleared, the object is marked **retained** and LeakCanary is notified. Before deciding anything it forces a garbage collection and counts again, so an object that was merely waiting for a GC drops out. "Retained" means "potentially leaking", not "proven leaking": the heap analysis decides that. ## When the heap is dumped A heap dump freezes the app, so LeakCanary batches retained objects: - **App visible** (at least one activity started): it waits until `retainedVisibleThreshold` objects are retained, **5 by default**, shows a notification with the current count and rechecks about every 2 seconds. - **App not visible**: once the app has been in the background for the watch delay, any retained object triggers a dump. Pressing Home after seeing the notification is a quick way to get the dump. - **Notification tapped**: the dump happens immediately. - **Rate limit**: dumps are at least 60 seconds apart. - **Debugger attached**: no dump, because a thread paused on a breakpoint creates temporary leaks; `dumpHeapWhenDebugging` defaults to `false`. - **Tests**: when `org.junit.Test` is on the classpath, heap dumping and analysis are disabled. The threshold is configurable with `LeakCanary.config = LeakCanary.config.copy(retainedVisibleThreshold = 3)`; a higher value interrupts developers less but may miss leaks. ## The rotation scenario Take a screen that registers itself as a listener with an app-wide singleton in `onCreate()` and never unregisters. Each rotation destroys the old activity instance and creates a new one. `ActivityWatcher` hands every destroyed instance to the object watcher; 5 seconds later each is still reachable through the singleton's listener list, so the retained count climbs by one per rotation. Once the fifth instance is retained (with the app in the foreground), LeakCanary dumps the heap, and the analysis groups all five into a single leak because they share one cause. ## Changing what is watched - To watch your own objects, call `AppWatcher.objectWatcher.expectWeaklyReachable()` when they should be gone. - To drop a default watcher, disable the automatic install with the `leak_canary_watcher_auto_install` resource and call `AppWatcher.manualInstall(application, watchersToInstall = AppWatcher.appDefaultWatchers(application).filter { it !is ServiceWatcher })`. - To change the delay, pass `retainedDelayMillis` to `manualInstall()`.
- Why does LeakCanary wait for 5 retained objects instead of dumping on the first one?Dumping the heap freezes the app, and the Android framework has known leaks the developer cannot easily fix, so dumping on every retained object would interrupt debugging constantly. Batching to `retainedVisibleThreshold` (5 by default) while the app is visible trades a little delay for fewer freezes. When the app is in the background nobody is interrupted, so one retained object is enough.
- Can a retained object turn out not to be a leak?Yes. Retained only means the weak reference was still set 5 seconds after the object should have become unreachable, even after a forced GC. Something may still be finishing with it, such as a slow callback. The heap analysis is what finds a strong reference path from a GC root; if none exists by then, there is no leak trace for that object.
A hotel checks each room five minutes after checkout and flags it if someone is still inside. While the hotel is busy, the manager is only called once five rooms are flagged; at night, one flagged room is enough.
- LeakCanary only watches activities, nothing else
- An object is reported as a leak the instant onDestroy() returns
- LeakCanary dumps the heap for every single retained object while you use the app
- Retained means LeakCanary has proven the object is leaking
- Turning dumpHeap off also stops LeakCanary from tracking retained objects
Assumes LeakCanary 2.14; the four default watchers, including RootViewWatcher and ServiceWatcher, are the set since 2.6, and the AppWatcher.config flags are deprecated in favour of AppWatcher.manualInstall().