LeakCanary原理

LeakCanary

参考:https://github.com/square/leakcanary/wiki/FAQ#how-does-it-work

https://blog.csdn.net/xinzhou201/article/details/78637700

GitHub上关于LeakCanary的原理:

  1. RefWatcher.watch() creates a KeyedWeakReference to the watched object.
  2. Later, in a background thread, it checks if the reference has been cleared and if not it triggers a GC.
  3. If the reference is still not cleared, it then dumps the heap into a .hprof file stored on the file system.
  4. HeapAnalyzerService is started in a separate process and HeapAnalyzer parses the heap dump using HAHA.
  5. HeapAnalyzer finds the KeyedWeakReference in the heap dump thanks to a unique reference key and locates the leaking reference.
  6. HeapAnalyzer computes the shortest strong reference path to the GC Roots to determine if there is a leak, and then builds the chain of references causing the leak.
  7. The result is passed back to DisplayLeakService in the app process, and the leak notification is shown.

这个涉及到弱引用的概念,可以参考https://blog.csdn.net/mazhimazh/article/details/19752475, 其中关于四四种的概念和使用场景进行了清除的介绍。单拿弱引用来说,弱引用不管内存是否够用,在GC的是时候都会被回收,主要用于引用的对象有自己的生命周期,而我们又不想影响对象生命周期的情况下,用于检测Activity/Fragment的内存泄露再合适不过。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2018 - 2022 得一 All Rights Reserved.

访客数 : | 访问量 :