LeakCanary 學習筆記

LeakCanary

在 Appliaction 中初始化 LeakCanary

if(!LeakCanary.isInAnalyzerProcess(this)){
    LeakCanary.install(this);
}

創(chuàng)建一個 RefWatcher 對象

public static RefWatcher install(Application application) {
  return refWatcher(application).listenerServiceClass(DisplayLeakService.class)
      .excludedRefs(AndroidExcludedRefs.createAppDefaults().build())
      .buildAndInstall();
}

監(jiān)聽 Activity 生命周期

public void watchActivities() {
  // Make sure you don't get installed twice.
  stopWatchingActivities();
  application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
}

關(guān)注 Activity 的 onDestroy 生命周期

private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
    new Application.ActivityLifecycleCallbacks() {
      @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
      }
      @Override public void onActivityStarted(Activity activity) {
      }
      @Override public void onActivityResumed(Activity activity) {
      }
      @Override public void onActivityPaused(Activity activity) {
      }
      @Override public void onActivityStopped(Activity activity) {
      }
      @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
      }
      @Override public void onActivityDestroyed(Activity activity) {
        ActivityRefWatcher.this.onActivityDestroyed(activity);
      }
    };

當 Activity 調(diào)用了 onDestroy() 方法后,RefWatcher 開始監(jiān)聽 Activity 對象

void onActivityDestroyed(Activity activity) {
  refWatcher.watch(activity);
}

第一步:使用 KeyedWeakReference 弱引用 Activity 對象,并且使用了 ReferenceQueue ,這里的 queue 表示,如果 activity 被 gc 回收了,那么 activity 就會被放入 queue 這個隊列中。

給當前對象生成一個唯一的 key 標識:String key = UUID.randomUUID().toString();
將生成的 key 添加到 Set 集合中:retainedKeys.add(key);

這里的 retainedKeys 集合的作用:放入到這個集合中的每一個元素是一個個 Key ,每一個 key 表示一個引用對象,也就是說只要這個 retainedKeys 存在元素,那么對應元素表示的引用對象就還沒有被回收。

第二步:在異步線程中去開始檢測這個 activity 是否發(fā)生內(nèi)存泄露了。

這里是在線程池中執(zhí)行

public void watch(Object watchedReference, String referenceName) {
  if (this == DISABLED) {
    return;
  }
  checkNotNull(watchedReference, "watchedReference");
  checkNotNull(referenceName, "referenceName");
  final long watchStartNanoTime = System.nanoTime();
  String key = UUID.randomUUID().toString();
  retainedKeys.add(key);
  final KeyedWeakReference reference =
      new KeyedWeakReference(watchedReference, key, referenceName, queue);
  ensureGoneAsync(watchStartNanoTime, reference);
}

第一步:removeWeaklyReachableReferences();先檢測一遍,queue 中引用是否出現(xiàn)在 retainedKeys 中,如果存在就要將這個引用對象對應的 key 從 retainedKeys 中移除

第二步:判斷是否是在 debug 狀態(tài),如果是,則返回 RETRY ,那么這個任務將會重新被執(zhí)行

第三步:在第一步檢測之后,如果在這一步中,對象就已經(jīng)被回收了,當前要檢測的 activity 對象對應的 key 就從 retainedKeys 中移除了,那么 gone(reference) 方法一定會返回 true ,那么 ensureGone 返回 DONE ,表示不再監(jiān)聽這個對象,表示對象被移除了。如果第一步操作之后發(fā)現(xiàn)對象還是沒有被回收,那么 gone(reference) 會返回 false

第四步:gcTrigger.runGc(); 執(zhí)行 gc 操作,因為 activity 是在弱引用的,因此在 gc 時不管是否內(nèi)存充足,弱引用的對象都會被回收。這里再次執(zhí)行第一步中的removeWeaklyReachableReferences()操作再次地檢測當前 activity 是否被回收。

第五步:執(zhí)行第三步再次判斷 activity 對象是否被回收了,如果被回收了,那么 ensureGone 返回 GONE 表示檢測完畢,該對象沒有發(fā)生內(nèi)存泄露。如果檢測到對象在 GC 之后,依舊沒有被回收,那就要開始分析 activity 的引用鏈。

Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
  long gcStartNanoTime = System.nanoTime();
  long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
  removeWeaklyReachableReferences();
  if (debuggerControl.isDebuggerAttached()) {
    // The debugger can create false leaks.
    return RETRY;
  }
  if (gone(reference)) {
    return DONE;
  }
  gcTrigger.runGc();
  removeWeaklyReachableReferences();
  if (!gone(reference)) {
    long startDumpHeap = System.nanoTime();
    long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
    File heapDumpFile = heapDumper.dumpHeap();
    if (heapDumpFile == RETRY_LATER) {
      // Could not dump the heap.
      return RETRY;
    }
    long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
    heapdumpListener.analyze(
        new HeapDump(heapDumpFile, reference.key, reference.name, excludedRefs, watchDurationMs,
            gcDurationMs, heapDumpDurationMs));
  }
  return DONE;
}

當前 activity 在二次確定之后還是沒有被回收,現(xiàn)在開始 dump 堆中內(nèi)存數(shù)據(jù)并保存到一個文件中 heapDumpFile 保存。

File heapDumpFile = heapDumper.dumpHeap();

heapdumpListener.analyze 分析 dump 出來的數(shù)據(jù)。

@Override public void analyze(HeapDump heapDump) {
  checkNotNull(heapDump, "heapDump");
  HeapAnalyzerService.runAnalysis(context, heapDump, listenerServiceClass);
}

HeapAnalyzerService 是一個 IntentService ,之所以使用 IntentService ,它是一個 Service 組件,所以優(yōu)先級比較高,不易被系統(tǒng) kill,并且內(nèi)部使用 HandlerThread 實現(xiàn)的異步線程去分析內(nèi)存泄露。

@Override protected void onHandleIntent(Intent intent) {
  if (intent == null) {
    CanaryLog.d("HeapAnalyzerService received a null intent, ignoring.");
    return;
  }
  String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
  HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);
  HeapAnalyzer heapAnalyzer = new HeapAnalyzer(heapDump.excludedRefs);
  AnalysisResult result = heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey);
  AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
}

checkForLeak 找到最短的 GCRoots 引用路徑。

public AnalysisResult checkForLeak(File heapDumpFile, String referenceKey) {
  long analysisStartNanoTime = System.nanoTime();
  if (!heapDumpFile.exists()) {
    Exception exception = new IllegalArgumentException("File does not exist: " + heapDumpFile);
    return failure(exception, since(analysisStartNanoTime));
  }
  try {
    HprofBuffer buffer = new MemoryMappedFileBuffer(heapDumpFile);
    HprofParser parser = new HprofParser(buffer);
    Snapshot snapshot = parser.parse();
    deduplicateGcRoots(snapshot);
    Instance leakingRef = findLeakingReference(referenceKey, snapshot);
    // False alarm, weak reference was cleared in between key check and heap dump.
    if (leakingRef == null) {
      return noLeak(since(analysisStartNanoTime));
    }
    return findLeakTrace(analysisStartNanoTime, snapshot, leakingRef);
  } catch (Throwable e) {
    return failure(e, since(analysisStartNanoTime));
  }
}

分析完畢之后,將結(jié)果發(fā)送出來。

AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
  • onHeapAnalyzed 發(fā)送一個通知
  • heapDump.heapDumpFile.delete(); 將 dump 文件刪除
@Override protected final void onHandleIntent(Intent intent) {
  HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAP_DUMP_EXTRA);
  AnalysisResult result = (AnalysisResult) intent.getSerializableExtra(RESULT_EXTRA);
  try {
    onHeapAnalyzed(heapDump, result);
  } finally {
    //noinspection ResultOfMethodCallIgnored
    heapDump.heapDumpFile.delete();
  }
}

可以覆寫這個方法,在分析完畢之后,將對應的數(shù)據(jù)上傳到后臺服務器。

/**
 * You can override this method and do a blocking call to a server to upload the leak trace and
 * the heap dump. Don't forget to check {@link AnalysisResult#leakFound} and {@link
 * AnalysisResult#excludedLeak} first.
 */
protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
}```

記錄于2021年5月30日

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容