Sobes.tech
Middle+

Как LeakCanary обнаруживает утечку памяти?

sobes.tech AI

Vastus AI-lt

LeakCanary works in several stages:

  1. Leak detection: It monitors the lifecycle of observed objects such as Fragment, Activity, View. When such an object is destroyed, LeakCanary places it in a WeakReference and triggers garbage collection.
  2. Reference check: After garbage collection, LeakCanary checks if a reference to the object still exists. If it does, it indicates that the object was not collected and a leak likely occurred.
  3. Heap dump: If a potential leak is detected, LeakCanary performs a heap dump of the application. This is a snapshot of all memory occupied by application objects at a specific moment.
  4. Object graph analysis: LeakCanary analyzes the object graph in the heap dump to find a path from GC roots to the suspected leaking object. This path shows why the object was not collected.
  5. Report display: Based on the analysis, LeakCanary generates a report with detailed leak information, including the retention path (the object holding a reference to the leaked object), object type, and location in the code where the leak probably occurred. The report is displayed as a notification or within the app.
// Example of simple object A tracking after its destruction
@Override
protected void onDestroy() {
    super.onDestroy();
    // Wrap the object in a WeakReference and pass it to LeakCanary
    refWatcher.watch(this);
}

LeakCanary uses its own parsers and algorithms to analyze hprof files (heap dump format) to efficiently find object retention paths.