Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 內存洩露檢測工具 LeakCanary 的前世今生

編輯:關於 Android 程式設計

曾經,我們是怎麼檢測內存洩露的

在 LeakCanary 出現之前,排查一場 OutOfMemoryError 是一段漫長的體力活。

第一步:收集線上問題。透過 Bugly、友盟這類統計平台彙整 Crash,先摸清 OOM 的規模與分布。

第二步:重現問題。對 Crash 做篩選、歸類、排除干擾項,然後設法在本機重演。有些問題只出現在特定機型上,於是為了湊齊設備,什麼方法都得用上——我曾待過的公司甚至專門派人去租了 50 台手機回來,一天六百塊。接著就是一遍遍嘗試,用最原始、最粗暴的方式還原當時的記憶體狀態。

第三步:Dump hprof。用 DDMS 觀察 Heap,手動觸發 GC(Cause GC),記錄記憶體變化,再導出 hprof 檔。重點看兩個數字:

  • Heap Size:堆的容量。當空餘空間不足時系統會擴大堆,但一旦超過該裝置允許的上限(例如某些手機給 App 的堆上限是 128MB),就會 OOM 並被殺進程。這個上限依機型記憶體與廠商定制而異。
  • Allocated:堆中實際已分配的大小,這才是 App 真正占用的量;資源正常回收後它會下降。

判斷方式很樸素:反覆打開、關閉同一個頁面,看堆是否單調遞增而不回落。

第四步:用 MAT 打開 hprof,逐一查找那些本該被回收卻還活着的物件。

第五步:計算該物件到 GC Roots 的最短強引用路徑。

第六步:找出路徑上哪一個引用是不該存在的,然後修掉它。

很麻煩,對吧?現在有個類庫能把這一切都自動化。

LeakCanary 的使用方式

在 Module.app 的 build.gradle 中引入:

dependencies {
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
}

注意 release 與 test 用的是 -no-op 版本,所有呼叫都是空實作,不帶入正式包。

然後在 Application 的 onCreate() 中安裝:

public class ExampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        LeakCanary.install(this);
    }
}

接著故意寫一段會洩露的程式碼。一旦偵測到洩露,通知欄就會跳出提示,點進去可看到完整的引用鏈。

它做到的事:以極低侵入性的方式自動捕捉記憶體洩漏,甚至能抓到 Android 系統元件自身的洩漏,而且完全省掉了「抓 Crash → 歸檔 → 重現場景 → Dump → MAT 分析」這整套流程。

原理分析

如果我們自己來實作

先別看源碼,設想要自己寫一個 LeakCanary,步驟大概是:

  1. 檢測某個物件是否已被回收。
  2. 若未被回收,Dump hprof,確認洩漏並導出最短引用路徑。
  3. 把路徑封裝成物件,用 Notification 展示,點擊跳轉到分析頁。

如何判斷物件是否被回收

除了 LeakCanary.install(this),官方 Demo 還示範了直接用 RefWatcher:

RefWatcher refWatcher = LeakCanary.androidWatcher(
        getApplicationContext(),
        new ServiceHeapDumpListener(getApplicationContext(), DisplayLeakService.class),
        AndroidExcludedRefs.createAppDefaults().build());
refWatcher.watch(this);

看 watch() 的實作:

public void watch(Object watchedReference, String referenceName) {
    Preconditions.checkNotNull(watchedReference, "watchedReference");
    Preconditions.checkNotNull(referenceName, "referenceName");

    // 若在 Debugger 跟蹤過程中,跳過檢測:此時的物件狀態不準確,且會干擾調試
    if (debuggerControl.isDebuggerAttached()) {
        return;
    }

    final long watchStartNanoTime = System.nanoTime();
    String key = UUID.randomUUID().toString();
    retainedKeys.add(key);

    final KeyedWeakReference reference =
            new KeyedWeakReference(watchedReference, key, referenceName, queue);

    watchExecutor.execute(new Runnable() {
        @Override
        public void run() {
            ensureGone(reference, watchStartNanoTime);
        }
    });
}

逐步拆解:

  1. 檢查參數非空。
  2. 若在除錯狀態則跳過監測——此時的引用狀態不可靠,還會干擾中斷點。
  3. 為每個監測對象產生 UUID 作為唯一鍵,存入 Set<String> retainedKeys,方便後續查找。
  4. 建立一個 KeyedWeakReference。它其實就是 WeakReference 的衍生類,額外帶上 key 與名稱——一個典型的裝飾模式應用。

這裡有兩個關鍵結構的分工:retainedKeys 代表「尚未被回收」的對象;而傳入 KeyedWeakReference 構造器的 referenceQueue,則會在對象被判定為弱引用可達後收到對應的弱引用通知,代表「已被回收」。兩邊一對照,就能判斷某個對象的生死。

  1. 最後透過自訂的 Executor 把任務派到背景執行。看 AndroidWatchExecutor:
public final class AndroidWatchExecutor implements Executor {

    static final String LEAK_CANARY_THREAD_NAME = "LeakCanary-Heap-Dump";
    private static final int DELAY_MILLIS = 5000;

    private final Handler mainHandler;
    private final Handler backgroundHandler;

    public AndroidWatchExecutor() {
        mainHandler = new Handler(Looper.getMainLooper());
        HandlerThread thread = new HandlerThread(LEAK_CANARY_THREAD_NAME);
        thread.start();
        backgroundHandler = new Handler(thread.getLooper());
    }

    @Override
    public void execute(final Runnable command) {
        if (isOnMainThread()) {
            executeDelayedAfterIdleUnsafe(command);
        } else {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    executeDelayedAfterIdleUnsafe(command);
                }
            });
        }
    }

    private boolean isOnMainThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    private void executeDelayedAfterIdleUnsafe(final Runnable runnable) {
        // 必須在主執行緒呼叫
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                backgroundHandler.postDelayed(runnable, DELAY_MILLIS);
                return false;
            }
        });
    }
}

它做的事:先確保任務從主執行緒發起,透過 IdleHandler 等到主線程序列空閒,再轉發到名為 LeakCanary-Heap-Dump 的後台執行緒,並延遲 5 秒執行。等空閒再檢查是刻意的設計——正在忙碌的畫面本就容易產生大量暫時性引用。

  1. 真正的檢測邏輯在 ensureGone():
void ensureGone(KeyedWeakReference reference, long watchStartNanoTime) {
    long gcStartNanoTime = System.nanoTime();
    long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);

    // 把 queue 中已回收的弱引用清掉,retainedKeys 只留還活着的
    removeWeaklyReachableReferences();

    // 已被回收,或在除錯中,直接返回
    if (gone(reference) || debuggerControl.isDebuggerAttached()) {
        return;
    }

    // 主動請求一次 GC,再重新清理
    gcTrigger.runGc();
    removeWeaklyReachableReferences();

    if (!gone(reference)) {
        long startDumpHeap = System.nanoTime();
        long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);

        File heapDumpFile = heapDumper.dumpHeap();
        if (heapDumpFile == null) {
            return;   // Dump 失敗,放棄本次
        }

        long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);

        heapdumpListener.analyze(new HeapDump(heapDumpFile, reference.key,
                reference.name, excludedRefs,
                watchDurationMs, gcDurationMs, heapDumpDurationMs));
    }
}

private boolean gone(KeyedWeakReference reference) {
    return !retainedKeys.contains(reference.key);
}

private void removeWeaklyReachableReferences() {
    // 弱引用一旦可達性消失就會入列,時機早於 finalize 與真正的回收
    KeyedWeakReference ref;
    while ((ref = (KeyedWeakReference) queue.poll()) != null) {
        retainedKeys.remove(ref.key);
    }
}

這裡有兩個值得深究的設計:

問題一:retainedKeys 和 queue 是怎麼關聯起來的?答案就在 removeWeaklyReachableReferences()。每次從 queue 取出被回收的弱引用,就把它對應的 key 從 retainedKeys 移除。於是 gone() 回傳 true 就代表該 key 已不在 retainedKeys 中,也就是對象已被回收,不必再觀察。

問題二:為什麼要呼叫兩次 removeWeaklyReachableReferences()?第一次是為了在「主動觸發 GC 之前」先撈一遍——如果對象早已被回收,就不必再花成本去通知 GC、Dump、分析。GC 執行緒的優先級極低,就算你通知了它也不一定馬上執行,所以選擇在什麼時機檢測,比檢測本身更關鍵。第二次則是在 GC 之後重新確認。

什麼時候該檢測

我們監測的對象是 Activity。Activity 有明確的生命週期,當它走完 onDestroy() 卻仍存活,就幾乎可以斷定洩漏。所以只要覆寫這個方法:

@Override
protected void onDestroy() {
    super.onDestroy();
    refWatcher.watch(this);
}

但我們顯然不想每個 Activity 都寫一遍。LeakCanary 的解法是透過 ActivityLifecycleCallbacks 統一轉發:

private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
        new Application.ActivityLifecycleCallbacks() {
    @Override public void onActivityCreated(Activity a, Bundle s) { }
    @Override public void onActivityStarted(Activity a) { }
    @Override public void onActivityResumed(Activity a) { }
    @Override public void onActivityPaused(Activity a) { }
    @Override public void onActivityStopped(Activity a) { }
    @Override public void onActivitySaveInstanceState(Activity a, Bundle b) { }

    @Override
    public void onActivityDestroyed(Activity activity) {
        ActivityRefWatcher.this.onActivityDestroyed(activity);
    }
};

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

因此在 Application 中只要一行 LeakCanary.install(this) 就足夠:

public final class LeakCanary {

    public static RefWatcher install(Application application) {
        return install(application, DisplayLeakService.class,
                AndroidExcludedRefs.createAppDefaults().build());
    }

    public static RefWatcher install(Application application,
                                     Class<? extends AbstractAnalysisResultService> listenerServiceClass,
                                     ExcludedRefs excludedRefs) {
        if (isInAnalyzerProcess(application)) {
            return RefWatcher.DISABLED;
        }
        enableDisplayLeakActivity(application);
        ServiceHeapDumpListener heapDumpListener =
                new ServiceHeapDumpListener(application, listenerServiceClass);
        RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
        ActivityRefWatcher.installOnIcsPlus(application, refWatcher);
        return refWatcher;
    }
}

但這個方法有個限制,源碼註釋寫得很明白:

// If you need to support Android < ICS, override onDestroy() in your base activity.

ActivityLifecycleCallbacks 是 API 14(Android 4.0)才有的。低於此版本,仍得回到覆寫 onDestroy() 的老路。另外,它只監測 Activity;Service、BroadcastReceiver 若要監測,得自己動手。

分析 hprof 檔

ServiceHeapDumpListener 本身只是轉發器:

public final class ServiceHeapDumpListener implements HeapDump.Listener {
    @Override
    public void analyze(HeapDump heapDump) {
        Preconditions.checkNotNull(heapDump, "heapDump");
        HeapAnalyzerService.runAnalysis(context, heapDump, listenerServiceClass);
    }
}

而 HeapAnalyzerService 是個 IntentService,運行在獨立進程中——因為分析 hprof 極耗記憶體,必須與主應用隔離:

public final class HeapAnalyzerService extends IntentService {

    private static final String LISTENER_CLASS_EXTRA = "listener_class_extra";
    private static final String HEAPDUMP_EXTRA = "heapdump_extra";

    public static void runAnalysis(Context context, HeapDump heapDump,
                                   Class<? extends AbstractAnalysisResultService> listenerServiceClass) {
        Intent intent = new Intent(context, HeapAnalyzerService.class);
        intent.putExtra(LISTENER_CLASS_EXTRA, listenerServiceClass.getName());
        intent.putExtra(HEAPDUMP_EXTRA, heapDump);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
        HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);

        ExcludedRefs androidDefaults = createAndroidDefaults().build();
        HeapAnalyzer heapAnalyzer = new HeapAnalyzer(androidDefaults, heapDump.excludedRefs);

        AnalysisResult result = heapAnalyzer.checkForLeak(
                heapDump.heapDumpFile, heapDump.referenceKey);

        AbstractAnalysisResultService.sendResultToListener(
                this, listenerClassName, heapDump, result);
    }
}

核心分析在 checkForLeak():

public AnalysisResult checkForLeak(File heapDumpFile, String referenceKey) {
    long analysisStartNanoTime = System.nanoTime();

    if (!heapDumpFile.exists()) {
        return AnalysisResult.failure(
                new IllegalArgumentException("File does not exist: " + heapDumpFile),
                since(analysisStartNanoTime));
    }

    ISnapshot snapshot = null;
    try {
        snapshot = openSnapshot(heapDumpFile);

        // 依 key 找回洩露的物件
        IObject leakingRef = findLeakingReference(referenceKey, snapshot);
        if (leakingRef == null) {
            // 誤報:弱引用在 key 檢查與 Dump 之間被清掉了
            return AnalysisResult.noLeak(since(analysisStartNanoTime));
        }

        String className = leakingRef.getClazz().getName();

        // 先求最短引用路徑(排除已知洩漏)
        AnalysisResult result =
                findLeakTrace(analysisStartNanoTime, snapshot, leakingRef, className, true);

        // 若排除後找不到,再不排除試一次
        if (!result.leakFound) {
            result = findLeakTrace(analysisStartNanoTime, snapshot, leakingRef, className, false);
        }
        return result;

    } catch (SnapshotException e) {
        return AnalysisResult.failure(e, since(analysisStartNanoTime));
    } finally {
        cleanup(heapDumpFile, snapshot);
    }
}

拿到最短引用路徑後,剩下的就是發送通知、點擊跳轉到分析 App 繪製路徑。

補充:排除干擾項

上面那段「先排除、找不到再不排除」的邏輯值得單獨說明:

private AnalysisResult findLeakTrace(long analysisStartNanoTime, ISnapshot snapshot,
        IObject leakingRef, String className, boolean excludingKnownLeaks)
        throws SnapshotException {

    ExcludedRefs excludedRefs = excludingKnownLeaks ? this.excludedRefs : baseExcludedRefs;

    PathsFromGCRootsTree gcRootsTree = shortestPathToGcRoots(snapshot, leakingRef, excludedRefs);
    if (gcRootsTree == null) {
        return AnalysisResult.noLeak(since(analysisStartNanoTime));
    }

    LeakTrace leakTrace = buildLeakTrace(snapshot, gcRootsTree, excludedRefs);
    return AnalysisResult.leakDetected(!excludingKnownLeaks, className,
            leakTrace, since(analysisStartNanoTime));
}

唯一的差別是 excludingKnownLeaks——是否排除已知的內存洩漏。

原因很實際:Android 系統本身存在若干已知洩漏,上層 App 工程師無能為力。若不排除,一打開 App 就彈出一堆莫名其妙又修不了的警告,反而干擾真正該處理的問題。做成參數讓使用者自行選擇,對 Framework 工程師或需要做 ROM 的團隊尤其有用。

這份清單由 ExcludedRefs 承載:

public final class ExcludedRefs implements Serializable {

    public final Map<String, Set<String>> excludeFieldMap;
    public final Map<String, Set<String>> excludeStaticFieldMap;
    public final Set<String> excludedThreads;

    private ExcludedRefs(Map<String, Set<String>> excludeFieldMap,
                         Map<String, Set<String>> excludeStaticFieldMap,
                         Set<String> excludedThreads) {
        // 複製一份並轉為不可變集合
        this.excludeFieldMap = unmodifiableMap(new LinkedHashMap<>(excludeFieldMap));
        this.excludeStaticFieldMap = unmodifiableMap(new LinkedHashMap<>(excludeStaticFieldMap));
        this.excludedThreads = unmodifiableSet(new LinkedHashSet<>(excludedThreads));
    }

    public static final class Builder {
        private final Map<String, Set<String>> excludeFieldMap = new LinkedHashMap<>();
        private final Map<String, Set<String>> excludeStaticFieldMap = new LinkedHashMap<>();
        private final Set<String> excludedThreads = new LinkedHashSet<>();

        /** 排除某類別的某個 instance 欄位 */
        public Builder instanceField(String className, String fieldName) {
            add(excludeFieldMap, className, fieldName);
            return this;
        }

        /** 排除某類別的某個 static 欄位 */
        public Builder staticField(String className, String fieldName) {
            add(excludeStaticFieldMap, className, fieldName);
            return this;
        }

        /** 排除某個執行緒 */
        public Builder thread(String threadName) {
            excludedThreads.add(threadName);
            return this;
        }

        private void add(Map<String, Set<String>> map, String className, String fieldName) {
            Set<String> fields = map.get(className);
            if (fields == null) {
                fields = new LinkedHashSet<>();
                map.put(className, fields);
            }
            fields.add(fieldName);
        }

        public ExcludedRefs build() {
            return new ExcludedRefs(excludeFieldMap, excludeStaticFieldMap, excludedThreads);
        }
    }
}

回顧

LeakCanary 的價值不只在「自動化」,更在於它把一套原本只有資深工程師才玩得動的流程——弱引用監測、延遲 GC 時機、hprof 解析、最短強引用路徑計算、干擾項排除——封裝成一行 install()。它背後的每個設計選擇,幾乎都對應著實戰中踩過的坑:為什麼等 Idle 才檢查、為什麼呼叫兩次清理、為什麼分析要放獨立進程、為什麼預設排除系統已知洩漏。讀懂這些,比單純會用這個庫有價值得多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved