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