监测内存泄漏--LeakCanary源码分析

作者: 秋阳君 | 来源:发表于2018-11-07 20:25 被阅读22次

1 在全局Application类中注册:

LeakCanary.install(this);
点进去看源码:

  public static RefWatcher install(Application application) {
    return refWatcher(application)         // 1-1
        .listenerServiceClass(DisplayLeakService.class)  // 1-2
        .excludedRefs(AndroidExcludedRefs.createAppDefaults().build())  //1-3
        .buildAndInstall();   // 1-4 和 2-1
  }

源码分为四部分:

  • 1-1 refWatcher(application) 创建一个 AndroidRefWatcherBuilder 对象
  • 1-2 .listenerServiceClass(DisplayLeakService.class) 传入DisplayLeakService,该Service的主要作用是分析内存堆信息,分析出内存泄漏的位置;
  • 1-3 .excludedRefs(AndroidExcludedRefs.createAppDefaults().build())
    • 1-3-1 AndroidExcludedRefs.createAppDefaults().build() 帮助分析跟踪泄漏的轨迹的对象
  • 1-4 .buildAndInstall() 创建RefWatcher对象

2 RefWatcher 监听内存泄漏(1-4中开始):

2-1RefWatcher将全局的context传入

  public RefWatcher buildAndInstall() {
    RefWatcher refWatcher = build();
    if (refWatcher != DISABLED) {
      LeakCanary.enableDisplayLeakActivity(context);
      ActivityRefWatcher.install((Application) context, refWatcher);   //重点 2-2
    }
    return refWatcher;
  }

2-2创建一个ActivityRefWatcher()对象

 public static void install(Application application, RefWatcher refWatcher) {
    new ActivityRefWatcher(application, refWatcher).watchActivities();
  }

2-3 ActivityRefWather对象中的重点方法 监听Activity的生命周期,在Activity销毁时,调用RefWatcher的方法:

private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
      new Application.ActivityLifecycleCallbacks() {
        @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        }
​
        @Override public void onActivityStarted(Activity activity) {
        }
​
        @Override public void onActivityResumed(Activity activity) {
        }
​
        @Override public void onActivityPaused(Activity activity) {
        }
​
        @Override public void onActivityStopped(Activity activity) {
        }
​
        @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
        }
​
        @Override public void onActivityDestroyed(Activity activity) {
          ActivityRefWatcher.this.onActivityDestroyed(activity);   //重点调用 2-4
        }
      };

2-4 ActivityRefWatcher.this.onActivityDestroyed(activity) 将Activity添加到监测队列中:

  void onActivityDestroyed(Activity activity) {
    refWatcher.watch(activity);
  }
public void watch(Object watchedReference) {
    watch(watchedReference, "");
  }

3 watch()方法:将Activity封装为弱引用对象,查看是否被回收

public void watch(Object watchedReference, String referenceName) {
    if (this == DISABLED) {
      return;
    }
    checkNotNull(watchedReference, "watchedReference"); 
    checkNotNull(referenceName, "referenceName");
    final long watchStartNanoTime = System.nanoTime();
    String key = UUID.randomUUID().toString();
    retainedKeys.add(key);
    final KeyedWeakReference reference =
        new KeyedWeakReference(watchedReference, key, referenceName, queue);   //重点  3-1
​
    ensureGoneAsync(watchStartNanoTime, reference);// 重点 3-2
  }
  • 3-1 通过实例一个带有键值的弱引用 KeyedWeakReference,将Activity唯一标识;
  • 3-2 开启一个线程,开始监测该Activity是否被回收,在gc后会调用:
  private void ensureGoneAsync(final long watchStartNanoTime, final KeyedWeakReference reference) {
    watchExecutor.execute(new Retryable() {
      @Override public Retryable.Result run() {
        return ensureGone(reference, watchStartNanoTime);  //4-1
      }
    });
  }

4 监测分析的最重点方法 ensureGone()

Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
    long gcStartNanoTime = System.nanoTime(); 
    long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime); //gc结束的时间
​
    removeWeaklyReachableReferences();  // 4-1
​
    if (debuggerControl.isDebuggerAttached()) {
      // The debugger can create false leaks.
      return RETRY;
    }
    if (gone(reference)) {   // 4-2
      return DONE;
    }
    gcTrigger.runGc();  
    removeWeaklyReachableReferences();
    if (!gone(reference)) {
      long startDumpHeap = System.nanoTime();
      long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
​
      File heapDumpFile = heapDumper.dumpHeap();
      if (heapDumpFile == RETRY_LATER) {
        // Could not dump the heap.
        return RETRY;
      }
      long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
      heapdumpListener.analyze(
          new HeapDump(heapDumpFile, reference.key, reference.name, excludedRefs, watchDurationMs,
              gcDurationMs, heapDumpDurationMs));
    }
    return DONE;
  }
  • 4-1 removeWeaklyReachableReferences():将存入到ReferenceQueue<Object> queue这个队列中的、现在不为空的,将其对应的键值消除,剩下的就是为空的引用;
private void removeWeaklyReachableReferences() {
    // WeakReferences are enqueued as soon as the object to which they point to becomes weakly
    // reachable. This is before finalization or garbage collection has actually happened.
    KeyedWeakReference ref;
    while ((ref = (KeyedWeakReference) queue.poll()) != null) {
      retainedKeys.remove(ref.key);
    }
  }
  • 4-2 gone(reference) :当前 retainedKeys (是Set<String>类型) 中,已经没有改Activity对应的引用了,证明在4-1中,已经被移除;也证明了在引用队列queue中,该Activity不为空;
    该ReferenceQueue<Object> queue的作用是:每次WeakReference所指向的对象被GC后,这个弱引用都会被放入这个与之相关联的ReferenceQueue队列中。所以在队列中不为空的Activity就是被回收掉的Activity。
  private boolean gone(KeyedWeakReference reference) {
    return !retainedKeys.contains(reference.key);
  }

相关文章

  • 监测内存泄漏--LeakCanary源码分析

    1 在全局Application类中注册: LeakCanary.install(this);点进去看源码: 源码...

  • Android内存分析与监控

    1.查看GC日志 2,使用Profiler分析内存 3,使用LeakCanary监控内存泄漏 LeakCanary...

  • Android-LeakCanary

    概述 LeakCanary 是 Square 出品的基于 Android 平台的内存泄漏监测工具; Activit...

  • LeakCanary源码解析

    概述 LeakCanary是Android开发中非常常用的一个内存泄漏监测和分析工具。了解其工作原理,有助于对An...

  • LeakCanary源码解析

    LeakCanary源码解析 前言 对于内存泄漏的检测,基于MAT起点较高,所以一般我们都使用LeakCanary...

  • leakcanery2源码

    LeakCanary是Android上用于检查内存泄漏的工具,LeakCanary大大减少因内存泄漏导致的内存溢出...

  • 【Android测试】内存泄漏检测 LeakCanary

    什么是内存泄漏和内存溢出?内存泄漏有什么危害?LeakCanary检测内存泄漏? 内存泄漏(Memory Leak...

  • Android性能优化

    android内存监测 LeakCanary 详情一个可以检测程序在运行过程中发生的内存泄漏问题,通过简单的代码配...

  • LeakCanary核心源码解析

    今天来写一波内存泄漏工具LeakCanary的分析,也整理一下之前的笔记,废话不多说,源码整起来。 我用的1.5....

  • LeakCanary原理

    一、源码 LeakCanary内存分析模块,独立进程,包名:leakcanary,保持app进程独立。在Appli...

网友评论

    本文标题:监测内存泄漏--LeakCanary源码分析

    本文链接:https://www.haomeiwen.com/subject/rswfzftx.html