0%

Leak Canary——A memory leak detection library for Android and Java

A memory leak detection library for Android and Java.

“A small leak will sink a great ship.” - Benjamin Franklin

LeakCanary

Getting started

In your build.gradle:

1
2
3
4
5
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'
}

In your Application class:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class ExampleApplication extends Application {

@Override public void onCreate() {
super.onCreate();
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return;
}
LeakCanary.install(this);
// Normal app init code...
}
}

You’re good to go! LeakCanary will automatically show a notification when an activity memory leak is detected in your debug build.

Questions? Check out the FAQ!

icon_512.png

原理[2]

LeakCanary通过square自家的HAHA来自动化分析Android heap dumps,内部基于MAT, vshor/mat,AndroMAT来做Java和Android特定的heap分析,亮点则是其将需要人工分析的事情做到了完全自动化,并给出能帮助快速定位修复内存泄露的信息。

在Application中使用LeakCanary.install(this)后,LeakCanary就会自动install一个ActivityRefWatcher来自动化检测activity是否在onDestroy后有泄露。具体步骤大致是

  1. 自动把activity加入到KeyedWeakReference
  2. 在background线程中,检查onDestroy后reference是否被清除,且没有触发gc
  3. 如果reference没有被清除,则dump heap到一个hprof文件并保存到app文件系统中
  4. 在一个单独进程中启动HeapAnalyzerService,HeapAnalyzer使用HAHA来分析heap dump。
  5. HeapAnalyzer在heap dump中根据reference key找到KeyedWeakReference。
  6. HeapAnalyzer计算出到GC Roots的最短强引用路径来判断是否存在泄露,然后build出造成这个泄露的引用链。
  7. 结果被传回来app进程的DisplayLeakService,并展示一个泄露的notification。
  8. square称从用了LeakCanary后,发现并修复了很多他们app中的内存泄露,而且找到了一些Android SDK中的泄露,最终减少了94%因为OOM错误导致的crash。

Reference

[1]LeakCanary
[2]接入LeakCanary检测内存泄露

欢迎关注我的其它发布渠道