作家
登录

带你学开源项目:LeakCanary-如何检测 Activity 是否泄漏

作者: 来源: 2017-05-24 10:06:09 阅读 我要评论

return !retainedKeys.contains(reference.key); 
  • }private void removeWeaklyReachableReferences() { 
  •   KeyedWeakReference ref;  while ((ref = (KeyedWeakReference) queue.poll()) != null) { 
  •     retainedKeys.remove(ref.key); 
  •   } 
  •  
  • 1. 若何创建一个优先级低的主线程义务,它只会在主线程余暇时才履行,不会影响到app的机能?

    至此,核心的内存泄漏检测机制便看完了。

    1. Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {      @Override public boolean queueIdle() {        // do task 
    2.         return false; // only once 
    3.       } 
    4.     });  

    2. 若何快速创建一个主/子线程handler?

    1. //主线程handlermainHandler = new Handler(Looper.getMainLooper());//子线程handlerHandlerThread handlerThread = new HandlerThread(“子线程义务”); 
    2. handlerThread.start(); 
    3. Handler backgroundHandler = new Handler(handlerThread.getLooper());  
    1. Looper.getMainLooper().getThread() == Thread.currentThread(); 

    可以看到,它起首会向主线程的 MessageQueue 添加一个 IdleHandler 。

    System.gc() 可以触发急速 gc 吗?如不雅不可那怎么才能触发即时 gc 呢?

    在 LeakCanary 里,须要急速触发 gc,并在之后急速断定弱引用是否被收受接收。这意味着该 gc 必须可以或许急速同步履行。

    我们来看下其实现方法:

    1. /** 
    2.  * Indicates to the VM that it would be a good time to run the 
    3.  * garbage collector. Note that this is a hint only. There is no guarantee 
    4.  * that the garbage collector will actually be run. 
    5.  */public static void gc() {    boolean shouldRunGC;    synchronized(lock) { 
    6.         shouldRunGC = justRanFinalization;        if (shouldRunGC) { 
    7.             justRanFinalization = false
    8.         } else { 
    9.             runGC = true
    10.         } 
    11.     }    if (shouldRunGC) { 
    12.         Runtime.getRuntime().gc(); 
    13.     } 
    14.  

    注释里清跋扈说了, System.gc() 只是建议垃圾收受接收器来履行收受接收,然则 不克不及包管真的去收受接收 。大年夜代码也能看出,必须先断定 shouldRunGC 才能决定是否真的要 gc。


      推荐阅读

      一个可以查看Linux当前缓存了哪些大文件的小工具

    Linux 用户可能经常碰到的一个问题是,机械有 16GB 内存之多,运行的过程也不多,然则剩下的 free 内存并不多,大年夜部分都被 buff 和 cache 占用了(比如下面我的 PC)。$ free -h >>>详细阅读


    本文标题:带你学开源项目:LeakCanary-如何检测 Activity 是否泄漏

    地址:http://www.17bianji.com/lsqh/35385.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)