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

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 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类型) 中,已经没有改Activity对应的引用了,证明在4-1中,已经被移除;也证明了在引用队列queue中,该Activity不为空;
      该ReferenceQueue queue的作用是:每次WeakReference所指向的对象被GC后,这个弱引用都会被放入这个与之相关联的ReferenceQueue队列中。所以在队列中不为空的Activity就是被回收掉的Activity。
        private boolean gone(KeyedWeakReference reference) {
          return !retainedKeys.contains(reference.key);
        }
      
      • 4-3 引用队列ReferenceQueue源码分析 :
        https://blog.csdn.net/Jesministrator/article/details/78786162

      你可能感兴趣的:(监测内存泄漏--LeakCanary源码分析)