【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为我们分析出的导致泄漏的引用链:
在这里插入图片描述

原理

当调用了 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 中文使用说明

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kevin-Dev

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值