LeakCanary
提供了一種很便捷的方式,讓咱們在開發階段檢測內存泄漏問題,咱們不須要本身去根據內存快照來分析內存泄漏的緣由,所須要作的僅僅是在Debug
包中集成它,它會自動地幫咱們檢測內存泄漏,並給出致使泄漏的引用鏈。android
下面,就來看一下如何在項目當中集成它:bash
release
版本中,全部的調用都是空實現,這樣就會避免在release
的版本中也在桌面生成一個泄漏檢測結果的圖標。dependencies {
//在 debug 版本中才會實現真正的功能
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
//在 release 版本中爲空實現
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
複製代碼
Application
,初始化一個全局RefWatcher
對象,它負責監視全部應當要被回收的對象:public class LeakCanaryApplication extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context) {
LeakCanaryApplication application = (LeakCanaryApplication) context.getApplicationContext();
return application.mRefWatcher;
}
}
複製代碼
Activity
爲例就須要在它的onDestory()
方法中加入監測的代碼,咱們經過單例持有Activity
的引用,模擬了一種內存泄漏發生的場景: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;
}
}
public class LeakCanaryActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leak_canary);
//讓這個單例對象持有 Activity 的引用
LeakSingleton.getInstance(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//在 onDestroy 方法中使用 Application 中建立的 RefWatcher 監視須要回收的對象
LeakCanaryApplication.getRefWatcher(this).watch(this);
}
}
複製代碼
在退出應用程序以後,咱們會發如今桌面上生成了一個新的圖標,點擊圖標進入,就是LeakCanary
爲咱們分析出的致使泄漏的引用鏈: 服務器
LeakCanary
集成到項目中的方法,下面,咱們來討論一下它的實現原理。
當調用了RefWatcher.watch()
方法以後,會觸發如下邏輯:app
KeyedWeakReference
,它內部引用了watch
傳入的對象:final KeyedWeakReference reference = new KeyedWeakReference(watchedReference, key, referenceName, this.queue);
複製代碼
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
是會在桌面生成一個圖標,點擊圖標以後,會展現致使泄漏的引用鏈,有時候,咱們但願把這些信息上傳到服務器中,那麼就須要自定義收到結果後的處理的行爲,下面,咱們看一下要怎麼作:ide
DisplayLeakService
,進行本身的處理邏輯,這裏咱們只是打印出泄漏的信息,heapDump
爲對應的內存快照,result
爲分析的結果,leakInfo
則是相關的信息:public class MyLeakUploadService extends DisplayLeakService {
@Override
protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
Log.d("MyLeakUploadService", "leakInfo=" + leakInfo);
}
}
複製代碼
Application
中初始化RefWatcher
的方式,第二個參數中傳入咱們自定義的Service
類名:public class LeakCanaryApplication extends Application {
private RefWatcher mRefWatcher;
@Override
public void onCreate() {
super.onCreate();
mRefWatcher = LeakCanary.install(this, MyLeakUploadService.class);
}
}
複製代碼
AndroidManifest.xml
中註冊自定義的Service
:<application>
<service android:name=".leakcanary.MyLeakUploadService"/>
</application>
複製代碼
在調試階段,咱們能夠經過引入LeakCanary
,讓它幫助咱們排查出一些會致使內存泄漏的問題。post