簡介
使用 MAT 來分析記憶體問題,有一些門檻,會有一些難度,并且效率也不是很高,對于一個記憶體洩漏問題,可能要進行多次排查和對比才能找到問題的原因。為了能簡單迅速的發現記憶體洩漏,Square 公司基于 MAT 開源了 LeakCanary
使用
- 在 app/build.gradle 中加入引用:
dependencies {
//在 debug 版本中才會實作真正的功能
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
//在 release 版本中為空實作
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
}
- 在 Application 中:
public class MyApplication extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = setupLeakCanary();
}
private RefWatcher setupLeakCanary(){
if (LeakCanary.isInAnalyzerProcess(this)) {
return mRefWatcher.DISABLED;
}
return LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
MyApplication leakApplication = (MyApplication) context.getApplicationContext();
return leakApplication.mRefWatcher;
}
}
-
在需要回收的對象上,添加檢測代碼。
LeakSingleton.java
public class LeakSingleton {
private static LeakSingleton sInstance;
private Context mContext;
public static LeakSingleton getInstance(Context context) {
if (sInstance == null) {
sInstance = new LeakSingleton(context);
}
return sInstance;
}
private LeakSingleton(Context context) {
mContext = context;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//讓這個單例對象持有 Activity 的引用
LeakSingleton.getInstance(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在 onDestroy 方法中使用 Application 中建立的 RefWatcher 監視需要回收的對象
MyApplication.getRefWatcher(this).watch(this);
}
}
在退出應用程式之後,我們會發現在桌面上生成了一個新的圖示,點選圖示進入,就是LeakCanary為我們分析出的導緻洩漏的引用鍊:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcsQXYtJ3bm9CXldWYtlWPzNXZj9mcw1ycz9WL49jb1c0Y11kMNRzaq5EMJ1mW0MmeNNTUH10dJRFTy0ERPVTUU9Ee4k3YsR2VZRHbyg1aGJjYzJEWkZHOXFWdVhUY6VzVZBHctxkeWJjWoFzVhRXUXlld4d0YxkTeMZTTINGMShUYvwlbj5yZtlmbkN3YuQnclZnbvN2Ztl2Lc9CX6MHc0RHaiojIsJye.jpg)
原理
當調用了 RefWatcher.watch() 方法之後,會觸發以下邏輯:
- 建立一個 KeyedWeakReference,它内部引用了 watch 傳入的對象:
- 在背景線程檢查引用是否被清除:
this.watchExecutor.execute(new Runnable() {
public void run() {
RefWatcher.this.ensureGone(reference, watchStartNanoTime);
}
});
- 如果沒有清除,那麼首先調用一次GC,假如引用還是沒有被清除,那麼把目前的記憶體快照儲存到.hprof檔案當中,并調用heapdumpListener進行分析:
void ensureGone(KeyedWeakReference reference, long watchStartNanoTime) {
long gcStartNanoTime = System.nanoTime();
long watchDurationMs = TimeUnit.NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
this.removeWeaklyReachableReferences();
if(!this.gone(reference) && !this.debuggerControl.isDebuggerAttached()) {
this.gcTrigger.runGc();
this.removeWeaklyReachableReferences();
if(!this.gone(reference)) {
long startDumpHeap = System.nanoTime();
long gcDurationMs = TimeUnit.NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
File heapDumpFile = this.heapDumper.dumpHeap();
if(heapDumpFile == null) {
return;
}
long heapDumpDurationMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
this.heapdumpListener.analyze(new HeapDump(heapDumpFile, reference.key, reference.name, watchDurationMs, gcDurationMs, heapDumpDurationMs));
}
}
}
- 上面說到的heapdumpListener的實作類為ServiceHeapDumpListener,它會啟動内部的HeapAnalyzerService:
public void analyze(HeapDump heapDump) {
Preconditions.checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(this.context, heapDump, this.listenerServiceClass);
}
- 這是一個IntentService,是以它的onHandlerIntent方法是運作在子線程中的,在通過HeapAnalyzer分析完畢之後,把最終的結果傳回給App端展示檢測的結果:
protected void onHandleIntent(Intent intent) {
String listenerClassName = intent.getStringExtra("listener_class_extra");
HeapDump heapDump = (HeapDump)intent.getSerializableExtra("heapdump_extra");
AnalysisResult result = this.heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey);
AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
}
- HeapAnalyzer 會計算未能回收的引用到 Gc Roots 的最短引用路徑,如果洩漏,那麼建立導緻洩漏的引用鍊并通過 AnalysisResult傳回:
public AnalysisResult checkForLeak(File heapDumpFile, String referenceKey) {
long analysisStartNanoTime = System.nanoTime();
if(!heapDumpFile.exists()) {
IllegalArgumentException snapshot1 = new IllegalArgumentException("File does not exist: " + heapDumpFile);
return AnalysisResult.failure(snapshot1, this.since(analysisStartNanoTime));
} else {
ISnapshot snapshot = null;
AnalysisResult className;
try {
snapshot = this.openSnapshot(heapDumpFile);
IObject e = this.findLeakingReference(referenceKey, snapshot);
if(e != null) {
String className1 = e.getClazz().getName();
AnalysisResult result = this.findLeakTrace(analysisStartNanoTime, snapshot, e, className1, true);
if(!result.leakFound) {
result = this.findLeakTrace(analysisStartNanoTime, snapshot, e, className1, false);
}
AnalysisResult var9 = result;
return var9;
}
className = AnalysisResult.noLeak(this.since(analysisStartNanoTime));
} catch (SnapshotException var13) {
className = AnalysisResult.failure(var13, this.since(analysisStartNanoTime));
return className;
} finally {
this.cleanup(heapDumpFile, snapshot);
}
return className;
}
}
參考文獻
LeakCanary 中文使用說明