性能優(yōu)化工具知識梳理(1) - TraceView
性能優(yōu)化工具知識梳理(2) - Systrace
性能優(yōu)化工具知識梳理(3) - 調(diào)試GPU過度繪制 & GPU呈現(xiàn)模式分析
性能優(yōu)化工具知識梳理(4) - Hierarchy Viewer
性能優(yōu)化工具知識梳理(5) - MAT
性能優(yōu)化工具知識梳理(6) - Memory Monitor & Heap Viewer & Allocation Tracker
性能優(yōu)化工具知識梳理(7) - LeakCanary
性能優(yōu)化工具知識梳理(8) - Lint
一、概述
LeakCanary
提供了一種很便捷的方式,讓我們在開發(fā)階段檢測內(nèi)存泄漏問題硝逢,我們不需要自己去根據(jù)內(nèi)存快照來分析內(nèi)存泄漏的原因,所需要做的僅僅是在Debug
包中集成它绣檬,它會自動地幫我們檢測內(nèi)存泄漏,并給出導(dǎo)致泄漏的引用鏈嫂粟。
二娇未、集成
下面,就來看一下如何在項目當(dāng)中集成它:
- 第一步:需要引入遠(yuǎn)程依賴星虹,這里我們引入了兩個零抬,在
release
版本中,所有的調(diào)用都是空實現(xiàn)宽涌,這樣就會避免在release
的版本中也在桌面生成一個泄漏檢測結(jié)果的圖標(biāo)平夜。
dependencies {
//在 debug 版本中才會實現(xiàn)真正的功能
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
//在 release 版本中為空實現(xiàn)
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
- 第二步:重寫
Application
,初始化一個全局RefWatcher
對象卸亮,它負(fù)責(zé)監(jiān)視所有應(yīng)當(dāng)要被回收的對象:
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;
}
}
- 第三步:在需要回收的對象上忽妒,添加監(jiān)測代碼,這里我們以
Activity
為例就需要在它的onDestory()
方法中加入監(jiān)測的代碼兼贸,我們通過單例持有Activity
的引用段直,模擬了一種內(nèi)存泄漏發(fā)生的場景:
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 中創(chuàng)建的 RefWatcher 監(jiān)視需要回收的對象
LeakCanaryApplication.getRefWatcher(this).watch(this);
}
}
在退出應(yīng)用程序之后,我們會發(fā)現(xiàn)在桌面上生成了一個新的圖標(biāo)溶诞,點擊圖標(biāo)進(jìn)入鸯檬,就是LeakCanary
為我們分析出的導(dǎo)致泄漏的引用鏈:
以上就是把
LeakCanary
集成到項目中的方法,下面螺垢,我們來討論一下它的實現(xiàn)原理喧务。
三颜及、原理
當(dāng)調(diào)用了RefWatcher.watch()
方法之后,會觸發(fā)以下邏輯:
- 創(chuàng)建一個
KeyedWeakReference
蹂楣,它內(nèi)部引用了watch
傳入的對象:
final KeyedWeakReference reference = new KeyedWeakReference(watchedReference, key, referenceName, this.queue);
- 在后臺線程檢查引用是否被清除:
this.watchExecutor.execute(new Runnable() {
public void run() {
RefWatcher.this.ensureGone(reference, watchStartNanoTime);
}
});
- 如果沒有清除,那么首先調(diào)用一次
GC
讯蒲,假如引用還是沒有被清除痊土,那么把當(dāng)前的內(nèi)存快照保存到.hprof
文件當(dāng)中,并調(diào)用heapdumpListener
進(jìn)行分析:
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
的實現(xiàn)類為ServiceHeapDumpListener
墨林,它會啟動內(nèi)部的HeapAnalyzerService
:
public void analyze(HeapDump heapDump) {
Preconditions.checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(this.context, heapDump, this.listenerServiceClass);
}
- 這是一個
IntentService
赁酝,因此它的onHandlerIntent
方法是運行在子線程中的,在通過HeapAnalyzer
分析完畢之后旭等,把最終的結(jié)果傳回給App
端展示檢測的結(jié)果:
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
的最短引用路徑酌呆,如果泄漏,那么建立導(dǎo)致泄漏的引用鏈并通過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;
}
}
四搔耕、自定義處理行為
默認(rèn)LeakCanary
是會在桌面生成一個圖標(biāo)隙袁,點擊圖標(biāo)之后,會展示導(dǎo)致泄漏的引用鏈弃榨,有時候菩收,我們希望把這些信息上傳到服務(wù)器中,那么就需要自定義收到結(jié)果后的處理的行為鲸睛,下面娜饵,我們看一下要怎么做:
- 第一步:繼承
DisplayLeakService
,進(jìn)行自己的處理邏輯官辈,這里我們只是打印出泄漏的信息箱舞,heapDump
為對應(yīng)的內(nèi)存快照,result
為分析的結(jié)果拳亿,leakInfo
則是相關(guān)的信息:
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
的方式晴股,第二個參數(shù)中傳入我們自定義的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>
-
最后,我們運行和之前一樣的操作风瘦,會看到在輸出臺上打印出了泄漏的分析結(jié)果:
五队魏、小結(jié)
在調(diào)試階段,我們可以通過引入LeakCanary
万搔,讓它幫助我們排查出一些會導(dǎo)致內(nèi)存泄漏的問題胡桨。
六、參考文獻(xiàn)
更多文章瞬雹,歡迎訪問我的 Android 知識梳理系列:
- Android 知識梳理目錄:http://www.reibang.com/p/fd82d18994ce
- 個人主頁:http://lizejun.cn
- 個人知識總結(jié)目錄:http://lizejun.cn/categories/