一步步拆解 LeakCanary,源码解读-别再说你不知道HashMap原理

excludedRefs);

}


build 方法看到这里你是不是有一种很眼熟的感觉,没错,它运用了建造者模式,与我们 Android 中的 AlertDialog.build 同出一辙。 建造者模式(Builder)及其应用

RefWatcherBuilder 主要有几个重要的成员变量

  • watchExecutor : 线程控制器,在 onDestroy() 之后并且主线程空闲时执行内存泄漏检测

  • debuggerControl : 判断是否处于调试模式,调试模式中不会进行内存泄漏检测

  • gcTrigger : 用于 GC,watchExecutor 首次检测到可能的内存泄漏,会主动进行 GC,GC 之后会再检测一次,仍然泄漏的判定为内存泄漏,进行后续操作

  • heapDumper : dump 内存泄漏处的 heap 信息,写入 hprof 文件

  • heapDumpListener : 解析完 hprof 文件,进行回调,并通知 DisplayLeakService 弹出提醒

  • excludedRefs : 排除可以忽略的泄漏路径

接下来,我们一起来看一下 ActivityRefWatcher.install 方法

ActivityRefWatcher.install((Application) context, refWatcher);

public final class ActivityRefWatcher {

/** @deprecated Use {@link #install(Application, RefWatcher)}. */

@Deprecated

public static void installOnIcsPlus(Application application, RefWatcher refWatcher) {

install(application, refWatcher);

}

public static void install(Application application, RefWatcher refWatcher) {

new ActivityRefWatcher(application, refWatcher).watchActivities();

}

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);

}

};

private final Application application;

private final RefWatcher refWatcher;

/**

  • Constructs an {@link ActivityRefWatcher} that will make sure the activities are not leaking

  • after they have been destroyed.

*/

public ActivityRefWatcher(Application application, RefWatcher refWatcher) {

this.application = checkNotNull(application, “application”);

this.refWatcher = checkNotNull(refWatcher, “refWatcher”);

}

void onActivityDestroyed(Activity activity) {

refWatcher.watch(activity);

}

public void watchActivities() {

// Make sure you don’t get installed twice.

stopWatchingActivities();

application.registerActivityLifecycleCallbacks(lifecycleCallbacks);

}

public void stopWatchingActivities() {

application.unregisterActivityLifecycleCallbacks(lifecycleCallbacks);

}

}

install 来说,主要做以下事情

  • 创建 ActivityRefWatcher,并调用 watchActivities 监听 activity 的生命周期

  • 在 activity 被销毁的时候,会回调 lifecycleCallbacks 的 onActivityDestroyed 方法,这时候会调用 onActivityDestroyed 去分析,而 onActivityDestroyed 方法又会回调 refWatcher.watch(activity)

我们回到 refWatcher.watch 方法

public void watch(Object watchedReference) {

watch(watchedReference, “”);

}

/**

  • Watches the provided references and checks if it can be GCed. This method is non blocking,

  • the check is done on the {@link WatchExecutor} this {@link RefWatcher} has been constructed

  • with.

  • @param referenceName An logical identifier for the watched object.

*/

public void watch(Object watchedReference, String referenceName) {

if (this == DISABLED) {

return;

}

checkNotNull(watchedReference, “watchedReference”);

checkNotNull(referenceName, “referenceName”);

final long watchStartNanoTime = System.nanoTime();

// 保证 key 的唯一性

String key = UUID.randomUUID().toString();

// 添加到 set 集合中

retainedKeys.add(key);

// 穿件 KeyedWeakReference 对象

final KeyedWeakReference reference =

new KeyedWeakReference(watchedReference, key, referenceName, queue);

ensureGoneAsync(watchStartNanoTime, reference);

}

  • retainedKeys : 一个 Set 集合,每个检测的对象都对应着一个唯一的 key,存储在 retainedKeys 中

  • KeyedWeakReference : 自定义的弱引用,持有检测对象和对用的 key 值

我们先来看一下 KeyedWeakReference ,可以看到 KeyedWeakReference 继承于 WeakReference,并定义了 key,name 字段

final class KeyedWeakReference extends WeakReference {

public final String key;

public final String name;

KeyedWeakReference(Object referent, String key, String name,

ReferenceQueue referenceQueue) {

super(checkNotNull(referent, “referent”), checkNotNull(referenceQueue, “referenceQueue”));

this.key = checkNotNull(key, “key”);

this.name = checkNotNull(name, “name”);

}

}

  • key 对应的 key 值名称

  • referenceQueue 引用队列,当结合 Refrence 使用的时候,垃圾回收器回收的时候,会把相应的对象加入到 refrenceQueue 中。

弱引用和引用队列 ReferenceQueue 联合使用时,如果弱引用持有的对象被垃圾回收,Java 虚拟机就会把这个弱引用加入到与之关联的引用队列中。即 KeyedWeakReference 持有的 Activity 对象如果被垃圾回收,该对象就会加入到引用队列 queue 中。具体的可以参考我的这一篇博客 java 源码系列 - 带你读懂 Reference 和 ReferenceQueue

ensureGoneAsync 方法

private void ensureGoneAsync(final long watchStartNanoTime, final KeyedWeakReference reference) {

watchExecutor.execute(new Retryable() {

@Override public Retryable.Result run() {

return ensureGone(reference, watchStartNanoTime);

}

});

}

ensureGoneAsync 这个方法,在 watchExecutor 的回调里面执行了 ensureGone 方法,watchExecutor 是 AndroidWatchExecutor 的实例。

接下来,我们一起来看一下 watchExecutor,主要关注 execute 方法

watchExecutor

public final class AndroidWatchExecutor implements WatchExecutor {

static final String LEAK_CANARY_THREAD_NAME = “LeakCanary-Heap-Dump”;

private final Handler mainHandler;

private final Handler backgroundHandler;

private final long initialDelayMillis;

private final long maxBackoffFactor;

public AndroidWatchExecutor(long initialDelayMillis) {

mainHandler = new Handler(Looper.getMainLooper());

HandlerThread handlerThread = new HandlerThread(LEAK_CANARY_THREAD_NAME);

handlerThread.start();

backgroundHandler = new Handler(handlerThread.getLooper());

this.initialDelayMillis = initialDelayMillis;

maxBackoffFactor = Long.MAX_VALUE / initialDelayMillis;

}

@Override public void execute(Retryable retryable) {

// 当前线程是主线程

if (Looper.getMainLooper().getThread() == Thread.currentThread()) {

waitForIdle(retryable, 0);

} else { // 当前线程不是主线程

postWaitForIdle(retryable, 0);

}

}


}

execute 方法,首先判断是否是主线程,如果是主线程,调用 waitForIdle 方法,等待空闲的时候执行,如果不是主线程,调用 postWaitForIdle 方法。我们一起来看一下 postWaitForIdle 和 waitForIdle 方法。

// 调用 mainHandler 的 post 方法,,确保在主线程中执行

void postWaitForIdle(final Retryable retryable, final int failedAttempts) {

mainHandler.post(new Runnable() {

@Override public void run() {

waitForIdle(retryable, failedAttempts);

}

});

}

// 当当前线程 looper 空闲的时候执行

void waitForIdle(final Retryable retryable, final int failedAttempts) {

// This needs to be called from the main thread.

// 当 looper 空闲的时候,会回调 queueIdle 方法

Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {

@Override public boolean queueIdle() {

postToBackgroundWithDelay(retryable, failedAttempts);

return false;

}

});

}

可以看到 postWaitForIdle 方法其实是 调用 mainHandler 的 post 方法,,确保在主线程中执行,之后再 runnable 的 run 方法在调用 waitForIdle 方法。而 waitForIdle 方法是在等当前 looper 空闲之后,执行 postToBackgroundWithDelay 方法

void postToBackgroundWithDelay(final Retryable retryable, final int failedAttempts) {

// 取 Math.pow(2, failedAttempts), maxBackoffFactor 的最小值,maxBackoffFactor = Long.MAX_VALUE / 5,

// 第一次执行的时候 failedAttempts 是 0 ,所以 exponentialBackoffFactor 是1

long exponentialBackoffFactor = (long) Math.min(Math.pow(2, failedAttempts), maxBackoffFactor);

// initialDelayMillis 的默认值是 5

long delayMillis = initialDelayMillis * exponentialBackoffFactor;

// 所以第一次延迟执行的时候是 5s,若

backgroundHandler.postDelayed(new Runnable() {

@Override public void run() {

Retryable.Result result = retryable.run();

// 过 result == RETRY,再次调用 postWaitForIdle,下一次的 delayMillis= 上一次的 delayMillis *2;

// 正常情况下,不会返回 RETRY,当 heapDumpFile == RETRY_LATER (即 dump heap 失败的时候),会返回 RETRY

if (result == RETRY) {

postWaitForIdle(retryable, failedAttempts + 1);

}

}

}, delayMillis);

}

postToBackgroundWithDelay 方法有点类似递归,正常情况下,若 retryable.run() 返回的结果不等于 RETRY,只会执行一次。若 retryable.run() 返回 RETRY,则会执行多次,退出的条件是 retryable.run() 返回结果不等于 RETRY;

delay 的时间 取 Math.pow(2, failedAttempts), maxBackoffFactor 两个数的最小值,maxBackoffFactor = Long.MAX_VALUE / 5,而,第一次执行的时候 failedAttempts 是 0 ,所以 exponentialBackoffFactor 是 1,即 delayMillis = initialDelayMillis * exponentialBackoffFactor= 5*1=5;

因此,综合上面的例子,第一次执行的时间是 activity destroy 之后 5s。

OK,我们回到 ensureGone 方法,这才是我们的重点

@SuppressWarnings(“ReferenceEquality”) // Explicitly checking for named null.

Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {

long gcStartNanoTime = System.nanoTime();

long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);

// 移除已经被回收的引用

removeWeaklyReachableReferences();

if (debuggerControl.isDebuggerAttached()) {

// The debugger can create false leaks.

return RETRY;

}

// 判断 reference,即 activity 是否内回收了,若被回收了,直接返回

if (gone(reference)) {

return DONE;

}

// 调用 gc 方法进行垃圾回收

gcTrigger.runGc();

// 移除已经被回收的引用

removeWeaklyReachableReferences();

// activity 还没有被回收,证明发生内存泄露

if (!gone(reference)) {

long startDumpHeap = System.nanoTime();

long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);

// dump heap,并生成相应的 hprof 文件

File heapDumpFile = heapDumper.dumpHeap();

if (heapDumpFile == RETRY_LATER) {// dump the heap 失败的时候

// Could not dump the heap.

return RETRY;

}

long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);

// 分析 hprof 文件

heapdumpListener.analyze(

new HeapDump(heapDumpFile, reference.key, reference.name, excludedRefs, watchDurationMs,

gcDurationMs, heapDumpDurationMs));

}

return DONE;

}

removeWeaklyReachableReferences 方法

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;

// 遍历 queue ,并从 retainedKeys set 集合中移除

while ((ref = (KeyedWeakReference) queue.poll()) != null) {

retainedKeys.remove(ref.key);

}

}

gone(reference) 方法,判断 retainedKeys set 集合,是否还含有 reference,若没有,证明已经被回收了;若含有,可能已经发生内存泄露。因为我们知道 refrence 被回收的时候,会被加进 queue 里面,值调用 gone 方法判断的时候,我们已经遍历 queue 移除掉 retainedKeys 里面的 refrence,若含有,证明 refrence 没有被回收,之所以说可能发生内存泄露,是因为 gc 回收器可能还没有回收。

private boolean gone(KeyedWeakReference reference) {

return !retainedKeys.contains(reference.key);

}

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
img

泄露,是因为 gc 回收器可能还没有回收。

private boolean gone(KeyedWeakReference reference) {

return !retainedKeys.contains(reference.key);

}

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级安卓工程师,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》送给大家,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
[外链图片转存中…(img-OKCUuqWr-1710931890465)]
[外链图片转存中…(img-agBNJx4n-1710931890466)]
[外链图片转存中…(img-HMJT8Eba-1710931890466)]
[外链图片转存中…(img-MJxXo2j8-1710931890467)]

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频
如果你觉得这些内容对你有帮助,可以添加下面V无偿领取!(备注Android)
[外链图片转存中…(img-rJu6mg9H-1710931890467)]

  • 15
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值