標籤:檔案 info source snapshot xmlns rod x86 mys ctas
LeakCanary
Android 和 Java 記憶體泄露檢測。
“A small leak will sink a great ship.” - Benjamin Franklin
千裡之堤, 毀於蟻穴。 -- 《韓非子·喻老》
demo
一個非常簡單的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo
開始使用
在 build.gradle 中加入引用,不同的編譯使用不同的引用:
dependencies { debugCompile ‘com.squareup.leakcanary:leakcanary-android:1.3‘ releaseCompile ‘com.squareup.leakcanary:leakcanary-android-no-op:1.3‘ }
在 Application 中:
public class ExampleApplication extends Application { @Override public void onCreate() { super.onCreate(); LeakCanary.install(this); }}
這樣,就萬事俱備了! 在 debug build 中,如果檢測到某個 activity 有記憶體泄露,LeakCanary 就是自動地顯示一個通知。
為什麼需要使用 LeakCanary?
問得好,看這個文章LeakCanary: 讓記憶體泄露無所遁形
如何使用
使用 RefWatcher 監控那些本該被回收的對象。
RefWatcher refWatcher = {...};// 監控refWatcher.watch(schrodingerCat);
LeakCanary.install() 會返回一個預定義的 RefWatcher,同時也會啟用一個 ActivityRefWatcher,用於自動監控調用 Activity.onDestroy() 之後泄露的 activity。
public class ExampleApplication extends Application { public static RefWatcher getRefWatcher(Context context) { ExampleApplication application = (ExampleApplication) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { super.onCreate(); refWatcher = LeakCanary.install(this); }}
使用 RefWatcher 監控 Fragment:
public abstract class BaseFragment extends Fragment { @Override public void onDestroy() { super.onDestroy(); RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity()); refWatcher.watch(this); }}
工作機制
RefWatcher.watch() 建立一個 KeyedWeakReference 到要被監控的對象。
然後在後台線程檢查引用是否被清除,如果沒有,調用GC。
如果引用還是未被清除,把 heap 記憶體 dump 到 APP 對應的檔案系統中的一個 .hprof 檔案中。
在另外一個進程中的 HeapAnalyzerService 有一個 HeapAnalyzer 使用HAHA 解析這個檔案。
得益於唯一的 reference key, HeapAnalyzer 找到 KeyedWeakReference,定位記憶體泄露。
HeapAnalyzer 計算 到 GC roots 的最短強引用路徑,並確定是否是泄露。如果是的話,建立導致泄露的引用鏈。
引用鏈傳遞到 APP 進程中的 DisplayLeakService, 並以通知的形式展示出來。
如何複製 leak trace?
在 Logcat 中,你可以看到類似這樣的 leak trace:
In com.example.leakcanary:1.0:1 com.example.leakcanary.MainActivity has leaked:* GC ROOT thread java.lang.Thread.<Java Local> (named ‘AsyncTask #1‘)* references com.example.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)* leaks com.example.leakcanary.MainActivity instance* Reference Key: e71f3bf5-d786-4145-8539-584afaecad1d* Device: Genymotion generic Google Nexus 6 - 5.1.0 - API 22 - 1440x2560 vbox86p* Android Version: 5.1 API: 22* Durations: watch=5086ms, gc=110ms, heap dump=435ms, analysis=2086ms
你甚至可以通過分享按鈕把這些東西分享出去。
SDK 導致的記憶體泄露
隨著時間的推移,很多SDK 和廠商 ROM 中的記憶體泄露問題已經被儘快修複了。但是,當這樣的問題發生時,一般的開發人員能做的事情很有限。
LeakCanary 有一個已知問題的忽略列表,AndroidExcludedRefs.java,如果你發現了一個新的問題,請提一個 issue 並附上 leak trace, reference key, 機器型號和 SDK 版本。如果可以附帶上 dump 檔案的 連結那就再好不過了。
對於最新發行的 Android,這點尤其重要。你有機會在協助在早期發現新的記憶體泄露,這對整個 Android 社區都有極大的益處。
開發版本的 Snapshots 包在這裡: Sonatype‘s snapshots repository。
leak trace 之外
有時,leak trace 不夠,你需要通過 MAT 或者 YourKit 深挖 dump 檔案。
通過以下方法,你能找到問題所在:
- 尋找所有的
com.squareup.leakcanary.KeyedWeakReference 執行個體。
- 檢查
key 欄位
- Find the
KeyedWeakReference that has a key field equal to the reference key reported by LeakCanary.
- 找到 key 和 和 logcat 輸出的 key 值一樣的
KeyedWeakReference。
referent 欄位對應的就是泄露的對象。
- 剩下的,就是動手修複了。最好是檢查到 GC root 的最短強引用路徑開始。
自訂UI 樣式
DisplayLeakActivity 有一個預設的表徵圖和標籤,你只要在你自己的 APP 資源中,替換以下資源就可。
res/ drawable-hdpi/ __leak_canary_icon.png drawable-mdpi/ __leak_canary_icon.png drawable-xhdpi/ __leak_canary_icon.png drawable-xxhdpi/ __leak_canary_icon.png drawable-xxxhdpi/ __leak_canary_icon.png
<?xml version="1.0" encoding="utf-8"?><resources> <string name="__leak_canary_display_activity_label">MyLeaks</string></resources>
儲存 leak trace
DisplayLeakActivity saves up to 7 heap dumps & leak traces in the app directory. You can change that number by providing R.integer.__leak_canary_max_stored_leaks in your app:
在 APP 的目錄中,DisplayLeakActivity 儲存了 7 個 dump 檔案和 leak trace。你可以在你的 APP 中,定義 R.integer.__leak_canary_max_stored_leaks 來覆蓋類庫的預設值。
<?xml version="1.0" encoding="utf-8"?><resources> <integer name="__leak_canary_max_stored_leaks">20</integer></resources>
上傳 leak trace 到伺服器
你可以改變處理完成的預設行為,將 leak trace 和 heap dump 上傳到你的伺服器以便統計分析。
建立一個 LeakUploadService, 最簡單的就是繼承 DisplayLeakService :
public class LeakUploadService extends DisplayLeakService { @Override protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) { if (!result.leakFound || result.excludedLeak) { return; } myServer.uploadLeakBlocking(heapDump.heapDumpFile, leakInfo); }}
請確認 release 版本 使用 RefWatcher.DISABLED:
public class ExampleApplication extends Application { public static RefWatcher getRefWatcher(Context context) { ExampleApplication application = (ExampleApplication) context.getApplicationContext(); return application.refWatcher; } private RefWatcher refWatcher; @Override public void onCreate() { super.onCreate(); refWatcher = installLeakCanary(); } protected RefWatcher installLeakCanary() { return RefWatcher.DISABLED; }}
自訂 RefWatcher:
public class DebugExampleApplication extends ExampleApplication { protected RefWatcher installLeakCanary() { return LeakCanary.install(app, LeakUploadService.class); }}
別忘了註冊 service:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" > <application android:name="com.example.DebugExampleApplication"> <service android:name="com.example.LeakUploadService" /> </application></manifest>
Android 記憶體流失分析利器——leakcanary