android检查内存泄露工具,Android 内存泄露检测工具 LeakCanary 的监控原理

本文详细介绍了Java中的四种引用类型:强引用、软引用、弱引用和虚引用,以及它们在内存管理中的作用。特别强调了弱引用和虚引用在内存敏感的缓存和垃圾回收中的角色。接着,文章讲解了LeakCanary内存泄漏检测库的工作原理,特别是RefWatcher如何通过弱引用和引用队列监控对象的回收情况,以及在Android应用中如何在Activity销毁时进行监控。最后,提到了LeakCanary在检测到内存泄漏时如何生成堆转储文件以便进一步分析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一. java 的几种 reference:

1,强引用(Strong Reference, 没有具体的类来标识强引用,正常的使用的对象引用都是强引用,由vm实现)

强引用是使用最普遍的引用。如果一个对象具有强引用,那垃圾回收器绝不会回收它。

当内存空间不足,Java虚拟机宁愿抛出OutOfMemoryError错误,使程序异常终止,也不会靠随意回收具有强引用的对象来解决内存不足的问题。

2,软引用(SoftReference)

如果一个对象只具有软引用,则内存空间足够,垃圾回收器就不会回收它;如果内存空间不足了,就会回收这些对象的内存。

只要垃圾回收器没有回收它,该对象就可以被程序使用。软引用可用来实现内存敏感的高速缓存。

软引用可以和一个引用队列(ReferenceQueue)联合使用,如果软引用所引用的对象被垃圾回收器回收,Java虚拟机就会把这个软引用加入到与之关联的引用队列中。

3,弱引用(WeakReference)

弱引用与软引用的区别在于:只具有弱引用的对象拥有更短暂的生命周期。

在垃圾回收器线程扫描它所管辖的内存区域的过程中,一旦发现了只具有弱引用的对象,不管当前内存空间足够与否,都会回收它的内存。

不过,由于垃圾回收器是一个优先级很低的线程,因此不一定会很快发现那些只具有弱引用的对象。

弱引用可以和一个引用队列(ReferenceQueue)联合使用,如果弱引用所引用的对象被垃圾回收,Java虚拟机就会把这个弱引用加入到与之关联的引用队列中。

4,虚引用(PhantomReference)

“虚引用”顾名思义,就是形同虚设,与其他几种引用都不同,虚引用并不会决定对象的生命周期。如果一个对象仅持有虚引用,那么它就和没有任何引用一样,在任何时候都可能被垃圾回收器回收。

虚引用主要用来跟踪对象被垃圾回收器回收的活动。虚引用与软引用和弱引用的一个区别在于:虚引用必须和引用队列 (ReferenceQueue)联合使用。

当垃圾回收器准备回收一个对象时,如果发现它还有虚引用,就会在回收对象的内存之前,把这个虚引用加入到与之 关联的引用队列中。

二.leakcanary原理

LeakCanary 中的 RefWatcher 就是通过弱引用及其队列来实现监控的:

有两个很重要的结构: retainedKeys 和 queue ,

retainedKeys 代表没被gc 回收的对象,

而queue中的弱引用代表的是被gc了的对象,通过这两个结构就可以监控对象是不是被回收了;

retainedKeys存放了RefWatcher为每个被监控的对象生成的唯一key;

同时每个被监控对象的弱引用(KeyedWeakReference)关联了 其对应的key 和 queue,这样对象若被回收,则其对应的弱引用会被入队到queue中;

removeWeaklyReachableReferences(..)所做的就是把存在与queue中的弱引用的key 从 retainedKeys 中删除。

private final Set retainedKeys;

private final ReferenceQueue queue;

/**

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

* the check is done on the {@link Executor} this {@link RefWatcher} has been constructed with.

*

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

*/

public void watch(Object watchedReference, String referenceName) {

checkNotNull(watchedReference, "watchedReference");

checkNotNull(referenceName, "referenceName");

if (debuggerControl.isDebuggerAttached()) {

return;

}

final long watchStartNanoTime = System.nanoTime();

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

retainedKeys.add(key);

final KeyedWeakReference reference =

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

watchExecutor.execute(new Runnable() {

@Override public void run() {

ensureGone(reference, watchStartNanoTime);

}

});

}

void ensureGone(KeyedWeakReference reference, long watchStartNanoTime) {

long gcStartNanoTime = System.nanoTime();

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

removeWeaklyReachableReferences();

if (gone(reference) || debuggerControl.isDebuggerAttached()) {

return;

}

gcTrigger.runGc();

removeWeaklyReachableReferences();

if (!gone(reference)) {

long startDumpHeap = System.nanoTime();

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

File heapDumpFile = heapDumper.dumpHeap();

if (heapDumpFile == HeapDumper.NO_DUMP) {

// Could not dump the heap, abort.

return;

}

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

heapdumpListener.analyze(

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

gcDurationMs, heapDumpDurationMs));

}

}

private boolean gone(KeyedWeakReference reference) {

return !retainedKeys.contains(reference.key);

}

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

}

}

什么时候使用RefWatcher进行监控 ?

对于android, 若要监控Activity, 需要在其执行destroy的 时候进行监控:

通过向Application 注册 ActivityLifecycleCallback, 在onActivityDestroyed(Activity activity) 中 开始监听 activity对象, 因为这时activity应该被回收了,若发生内存泄露,则可以没发现;

RefWatcher 检查对象是否被回收是在一个 Executor 中执行的, Android 的监控 提供了 AndroidWatchExecutor , 它在主线程执行, 但是有一个delay 时间(默认5000 milisecs), 因为对于application 来说,执行destroy activity只是把必要资源回收,activity 对象不一定会马上被 gc回收。

private void executeDelayedAfterIdleUnsafe(final Runnable runnable) {

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

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

@Override public boolean queueIdle() {

backgroundHandler.postDelayed(runnable, DELAY_MILLIS);

return false;

}

});

}

ActivityRefWatcher:

package com.squareup.leakcanary;

import android.annotation.TargetApi;

import android.app.Activity;

import android.app.Application;

import android.os.Bundle;

import static android.os.Build.VERSION.SDK_INT;

import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;

import static com.squareup.leakcanary.Preconditions.checkNotNull;

@TargetApi(ICE_CREAM_SANDWICH) public final class ActivityRefWatcher {

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

if (SDK_INT < ICE_CREAM_SANDWICH) {

// If you need to support Android < ICS, override onDestroy() in your base activity.

return;

}

ActivityRefWatcher activityRefWatcher = new ActivityRefWatcher(application, refWatcher);

activityRefWatcher.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, final 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);

}

}

若发生了泄露, refWatcher 会执行dump ,生成dump 文件,然后由mat 或haha 等分析工具找到泄露对象的引用路径。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值