Sobes.tech
Middle+

How does LeakCanary detect references to destroyed Activities?

sobes.tech AI

Answer from AI

LeakCanary uses a weak (Phantom Reference) or strong (Strong Reference) reference field in a special Observer that "listens" to the Activity's lifecycle. When the Activity is destroyed, LeakCanary records the time and waits for garbage collection. If after garbage collection the Activity object still exists in memory, LeakCanary initiates a heap dump, analyzes it, and builds an reachability graph to find the path from GC Roots to this "leaked" Activity.

Key steps:

  1. Lifecycle monitoring: LeakCanary registers ActivityLifecycleCallbacks.
  2. Bookmarking: When onDestroy() is called, LeakCanary creates a reference to the Activity (depending on the version) and records the timestamp.
  3. Waiting for GC: LeakCanary waits for garbage collection to occur to check if the object was destroyed.
  4. Post-GC check: If the Activity object is still accessible after GC, it indicates a potential leak.
  5. Heap dump: LeakCanary calls Debug.dumpHprofData() to save the current memory state.
  6. Dump analysis: LeakCanary (via Memory Analyzer Tool (MAT) or its own analyzer) scans the heap dump.
  7. Path finding: The tool finds paths in the object graph from GC Roots to the "leaked" Activity object.
  8. Report: LeakCanary generates a readable report showing the chain of references that prevents the object from being garbage collected.
How does LeakCanary detect references to destroyed… - sobes.tech