【Android -- 性能优化】内存分析工具 — LeakCanary

不断学习,做更好的自己

视频号 CSDN 简书
欢迎打开微信,关注我的视频号:程序员朵朵 点我 点我

简介

使用 MAT 来分析内存问题,有一些门槛,会有一些难度,并且效率也不是很高,对于一个内存泄漏问题,可能要进行多次排查和对比才能找到问题的原因。为了能简单迅速的发现内存泄漏,Square 公司基于 MAT 开源了 LeakCanary

使用

1. 在 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'
}

2. 在 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;
    }
}

3. 在需要回收的对象上,添加检测代码。
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为我们分析出的导致泄漏的引用链:
【Android -- 性能优化】内存分析工具 — LeakCanary_第1张图片

原理

当调用了 RefWatcher.watch() 方法之后,会触发以下逻辑:

  • 创建一个 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 中文使用说明

你可能感兴趣的:(Android,--,性能优化,LeakCanary,性能优化)