LeakCanary 源碼解析

一、 前言

1. Java 內(nèi)存模型
image.png
運(yùn)行時(shí)數(shù)據(jù)區(qū)域
名稱 特征 作用 配置參數(shù) 異常
程序計(jì)數(shù)器 占用內(nèi)存小,線程私有,生命周期與線程相同 大致為字節(jié)碼行號(hào)指示器
虛擬機(jī)棧 線程私有,生命周期與線程相同,使用連續(xù)的內(nèi)存空間 Java 方法執(zhí)行的內(nèi)存模型,存儲(chǔ)局部變量表、操作棧、動(dòng)態(tài)鏈接、方法出口等信息 -Xss StackOverflowError、OutOfMemoryError
java堆 線程共享,生命周期與虛擬機(jī)相同,可以不使用連續(xù)的內(nèi)存地址 保存對(duì)象實(shí)例,所有對(duì)象實(shí)例(包括數(shù)組)都要在堆上分配 -Xms、-Xsx、-Xmn OutOfMemoryError
方法區(qū) 線程共享,生命周期與虛擬機(jī)相同,可以不使用連續(xù)的內(nèi)存地址 存儲(chǔ)已被虛擬機(jī)加載的類信息、常量、靜態(tài)變量、即時(shí)編譯器編譯后的代碼等數(shù)據(jù) -XX:PermSize:16M 、-XX:MaxPermSize64M OutOfMemoryError
運(yùn)行時(shí)常量池 方法區(qū)的一部分,具有動(dòng)態(tài)性 存放字面量及符號(hào)引用
2. Java垃圾回收策略
  • 引用計(jì)數(shù)算法:給對(duì)象中添加一個(gè)引用計(jì)數(shù)器,每當(dāng)有引用它時(shí),計(jì)數(shù)器值就加1;當(dāng)引用失效時(shí),計(jì)數(shù)器值就減1;任何時(shí)刻計(jì)數(shù)器為0的對(duì)象就是不可能再被使用。
  • 可達(dá)性分析算法:通過一系列的稱為"GC Root"的對(duì)象作為起點(diǎn),從這些節(jié)點(diǎn)開始向下搜索,搜素所走過的路徑稱為引用鏈(Reference Chain),當(dāng)一個(gè)對(duì)象到GC Root沒有任何的引用鏈相連,就判定對(duì)象可以被回收
對(duì)象可達(dá)性
3. Java 四種引用類型
  • 強(qiáng)引用:默認(rèn)的引用方式,當(dāng)內(nèi)存空間不足,JVM寧愿觸發(fā)OOM,也不會(huì)對(duì)這部分內(nèi)存進(jìn)行回收。
Object obj = new Object();
obj = null;
  • 軟引用(SoftReference):當(dāng)內(nèi)存空間不足的時(shí)候,JVM會(huì)回收這部分內(nèi)存,一般用來做緩存策略。
  • 弱引用(WeakReference): 當(dāng)GC回收的時(shí)候,一旦發(fā)現(xiàn)了只具有弱引用的對(duì)象,不管當(dāng)前內(nèi)存空間足夠與否,都會(huì)回收這部分內(nèi)存。
  • 虛引用(PhantomReference):當(dāng) GC回收的時(shí)候會(huì)回收這部分內(nèi)存, 主要用于檢測對(duì)象是否已經(jīng)從內(nèi)存中刪除。
代碼示例
public class TestReference {

    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        String sw = "虛引用";

        switch (sw) {
            case "軟引用":
                Object objSoft = new Object();
                SoftReference<Object> softReference = new SoftReference<>(objSoft, referenceQueue);
                System.out.println("GC前獲取:" + softReference.get());
                objSoft = null;
                System.gc();
                Thread.sleep(1000);
                System.out.println("GC后獲取:" + softReference.get());
                System.out.println("隊(duì)列中的結(jié)果:" + referenceQueue.poll());
                break;
            case "弱引用":
                Object objWeak = new Object();
                WeakReference<Object> weakReference = new WeakReference<>(objWeak, referenceQueue);
                System.out.println("GC前獲取:" + weakReference.get());
                objWeak = null;
                System.gc();
                Thread.sleep(1000);
                System.out.println("GC后獲取:" + weakReference.get());
                System.out.println("隊(duì)列中的結(jié)果:" + referenceQueue.poll());
                break;
            case "虛引用":
                Object objPhan = new Object();
                PhantomReference<Object> phantomReference = new PhantomReference<>(objPhan, referenceQueue);
                System.out.println("GC前獲取:" + phantomReference.get());
                objPhan = null;
                System.gc();
                //此處的區(qū)別是當(dāng)objPhan的內(nèi)存被gc回收之前虛引用就會(huì)被加入到ReferenceQueue隊(duì)列中,其他的引用都為當(dāng)引用被gc掉時(shí)候,引用會(huì)加入到ReferenceQueue中
                Thread.sleep(1000);
                System.out.println("GC后獲取:" + phantomReference.get());
                System.out.println("隊(duì)列中的結(jié)果:" + referenceQueue.poll());
                break;
        }
    }
}

軟引用運(yùn)行結(jié)果:

軟引用運(yùn)行結(jié)果

弱引用運(yùn)行結(jié)果:

弱引用運(yùn)行結(jié)果

虛引用運(yùn)行結(jié)果:

虛引用運(yùn)行結(jié)果

二、 集成

build.gradle文件

dependencies {
   // debug 版本依賴
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.2'
  // release 版本依賴  
  releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.2'
  // 如果使用了 support fragment,請同時(shí)依賴
  debugImplementation 'com.squareup.leakcanary:leakcanary-support-fragment:1.6.2'

  // 最新2.0版本,只需要導(dǎo)入如下依賴,不再需要在Application里面添加其他代碼
  // debugImplementation because LeakCanary should only run in debug builds.
  // debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.0-alpha-2'
}

Application#onCreate方法

if (LeakCanary.isInAnalyzerProcess(this)) {
  // This process is dedicated to LeakCanary for heap analysis.
  // You should not init your app in this process.
  return;
}
LeakCanary.install(this);

三、 LeakCanary源碼導(dǎo)讀

3.1. LeakCanary項(xiàng)目架構(gòu)

LeakCanary 項(xiàng)目結(jié)構(gòu)圖:

LeakCanary項(xiàng)目結(jié)構(gòu)

  • leakcanary-analyzer : 負(fù)責(zé)分析內(nèi)存泄漏
  • leakcanary-android : android 核心模塊以及通知、界面展示等
  • leakcanary-android-instrumentation : 單元測試使用
  • leakcanary-sample : 使用案例
  • leakcanary-support-fragment : 支持 fragment v4包
  • leakcanary-watcher : 負(fù)責(zé)監(jiān)聽內(nèi)存泄漏
  • leakcanary-android-no-op : release 版本使用
3.2. LeakCanary執(zhí)行過程
LeakCanary執(zhí)行過程
3.3. LeakCanary初始化
  /**
   * Whether the current process is the process running the {@link HeapAnalyzerService}, which is
   * a different process than the normal app process.
   */
  public static boolean isInAnalyzerProcess(@NonNull Context context) {
    Boolean isInAnalyzerProcess = LeakCanaryInternals.isInAnalyzerProcess;
    // This only needs to be computed once per process.
    Log.d("LeakCanary", "isInAnalyzerProcess = " + isInAnalyzerProcess);
    if (isInAnalyzerProcess == null) {
      // HeapAnalyzerService進(jìn)程名是否等于主進(jìn)程名稱
      isInAnalyzerProcess = isInServiceProcess(context, HeapAnalyzerService.class);
      LeakCanaryInternals.isInAnalyzerProcess = isInAnalyzerProcess;
    }
    return isInAnalyzerProcess;
  }

  public static @NonNull void install(@NonNull Application application) {
    refWatcher(application)
        .listenerServiceClass(DisplayLeakService.class)  // 設(shè)置 heapDumpListener
        .excludedRefs(AndroidExcludedRefs.createAppDefaults().build()) // 去除Android SDK 引起的內(nèi)存泄漏
        .buildAndInstall();  //創(chuàng)建RefWatcher
  }

  public static @NonNull AndroidRefWatcherBuilder refWatcher(@NonNull Context context) {
    return new AndroidRefWatcherBuilder(context);
  }

isInAnalyzerProcess方法,用于檢測內(nèi)存分析進(jìn)程是否和主進(jìn)程名相同,如果是相同的,則設(shè)置RefWatcher = DISABLED ,不做任何處理。release 版本是通過以下以來確定的。
// release 版本依賴
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.2'

3.4 AndroidRefWatcherBuilder 對(duì)象
  public @NonNull AndroidRefWatcherBuilder listenerServiceClass(
      @NonNull Class<? extends AbstractAnalysisResultService> listenerServiceClass) {
    // isAssignableFrom()方法是判斷是否為某個(gè)類的父類,instanceof()方法是判斷是否某個(gè)類的子類。
    //(https://www.cnblogs.com/bethunebtj/p/4681438.html)
    enableDisplayLeakActivity = DisplayLeakService.class.isAssignableFrom(listenerServiceClass);
    return heapDumpListener(new ServiceHeapDumpListener(context, listenerServiceClass));
  }

  public final T heapDumpListener(HeapDump.Listener heapDumpListener) {
      this.heapDumpListener = heapDumpListener;
      return self();
  }

  public final T excludedRefs(ExcludedRefs excludedRefs) {
    heapDumpBuilder.excludedRefs(excludedRefs);
    return self();
  }

  @Override protected @NonNull HeapDumper defaultHeapDumper() {
    LeakDirectoryProvider leakDirectoryProvider =
        LeakCanaryInternals.getLeakDirectoryProvider(context);
    return new AndroidHeapDumper(context, leakDirectoryProvider);
  }

  public @NonNull RefWatcher buildAndInstall() {
    if (LeakCanaryInternals.installedRefWatcher != null) {
      throw new UnsupportedOperationException("buildAndInstall() should only be called once.");
    }
    RefWatcher refWatcher = build();
    if (refWatcher != DISABLED) {
      Log.d("LeakCanary", "enableDisplayLeakActivity = " + enableDisplayLeakActivity);
      if (enableDisplayLeakActivity) {
        LeakCanaryInternals.setEnabledAsync(context, DisplayLeakActivity.class, true);
      }
      Log.d("LeakCanary", "watchActivities = " + watchActivities);
      if (watchActivities) {
        ActivityRefWatcher.install(context, refWatcher);
      }
      Log.d("LeakCanary", "watchFragments = " + watchFragments);
      if (watchFragments) {
        FragmentRefWatcher.Helper.install(context, refWatcher);
      }
    }
    LeakCanaryInternals.installedRefWatcher = refWatcher;
    return refWatcher;
  }

  public final RefWatcher build() {
      if (isDisabled()) {
          return RefWatcher.DISABLED; 
      }
      if (heapDumpBuilder.excludedRefs == null) {
          heapDumpBuilder.excludedRefs(defaultExcludedRefs());
      }
      HeapDump.Listener heapDumpListener = this.heapDumpListener;
      if (heapDumpListener == null) {
          heapDumpListener = defaultHeapDumpListener();
      }
      DebuggerControl debuggerControl = this.debuggerControl;
      if (debuggerControl == null) {
          // 走這里
          debuggerControl = defaultDebuggerControl();
      }
      HeapDumper heapDumper = this.heapDumper;
      if (heapDumper == null) {
          // 走這里
          heapDumper = defaultHeapDumper();
      }
      WatchExecutor watchExecutor = this.watchExecutor;
      if (watchExecutor == null) {
          // 走這里
          watchExecutor = defaultWatchExecutor();
      }
      GcTrigger gcTrigger = this.gcTrigger;
      if (gcTrigger == null) {
          // 走這里
          gcTrigger = defaultGcTrigger();
      }
      if (heapDumpBuilder.reachabilityInspectorClasses == null) {
          heapDumpBuilder.reachabilityInspectorClasses(defaultReachabilityInspectorClasses());
      }
      return new RefWatcher(watchExecutor, debuggerControl, gcTrigger
                            , heapDumper, heapDumpListener, heapDumpBuilder);
  }

  @Override protected @NonNull WatchExecutor defaultWatchExecutor() {
    return new AndroidWatchExecutor(DEFAULT_WATCH_DELAY_MILLIS);
  }

buildAndInstall方法則用于設(shè)置heapDumpListener用于分析hprof文件, 過濾掉因?yàn)锳ndroid SDK引起的系統(tǒng)內(nèi)存泄漏引用, 展示DisplayLeakActivity桌面icon,監(jiān)聽Activity 以及Fragment生命周期,在其銷毀的時(shí)候調(diào)用RefWatcher的watch方法分析是否會(huì)發(fā)生內(nèi)存泄漏對(duì)象。build方法則是初始化RefWatcher對(duì)象,

關(guān)于設(shè)置DisplayLeakActivity enabled = true的地方,需要看看詳細(xì)的代碼

    LeakCanaryInternals.setEnabledAsync(context, DisplayLeakActivity.class, true);

    public static void setEnabledAsync(Context context, final Class<?> componentClass,
                                       final boolean enabled) {
        final Context appContext = context.getApplicationContext();
        AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
            @Override
            public void run() {
                setEnabledBlocking(appContext, componentClass, enabled);
            }
        });
    }

    public static void setEnabledBlocking(Context appContext, Class<?> componentClass,
                                          boolean enabled) {
        ComponentName component = new ComponentName(appContext, componentClass);
        PackageManager packageManager = appContext.getPackageManager();
        int newState = enabled ? COMPONENT_ENABLED_STATE_ENABLED : COMPONENT_ENABLED_STATE_DISABLED;
        // Blocks on IPC.
        packageManager.setComponentEnabledSetting(component, newState, DONT_KILL_APP);
    }

其實(shí)就是利用AsyncTask的THREAD_POOL_EXECUTOR線程池去執(zhí)行PackageManager的setComponentEnabledSetting方法,動(dòng)態(tài)設(shè)置COMPONENT_ENABLED_STATE_ENABLED


image.png
3.5 RefWatcher 對(duì)象
  private final Set<String> retainedKeys;
  private final ReferenceQueue<Object> queue; // 引用隊(duì)列

  public void watch(Object watchedReference) {
    watch(watchedReference, "");
  }

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

    ensureGoneAsync(watchStartNanoTime, reference);
  }

  private void ensureGoneAsync(final long watchStartNanoTime,
                               final KeyedWeakReference reference) {
    // 檢測線程調(diào)度器
    watchExecutor.execute(new Retryable() {
      @Override public Retryable.Result run() {
        return ensureGone(reference, watchStartNanoTime);
      }
    });
  }

  Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
    long gcStartNanoTime = System.nanoTime();
    long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);

    // 移除所有弱引用可達(dá)對(duì)象
    removeWeaklyReachableReferences();

    // 如果VM正連接到Debuger,忽略這次檢測,因?yàn)镈ebugger可能會(huì)持有一些在當(dāng)前上下文中不可見的對(duì)象,導(dǎo)致誤判
    if (debuggerControl.isDebuggerAttached()) {
      // The debugger can create false leaks.
      return RETRY;
    }
    //上面執(zhí)行 removeWeaklyReachableReferences 方法,判斷是不是監(jiān)視對(duì)象已經(jīng)被回收了,如果被回收了,那么說明沒有發(fā)生內(nèi)存泄漏,直接結(jié)束
    if (gone(reference)) {
      return DONE;
    }
     // 手動(dòng)觸發(fā)一次 GC 垃圾回收
    gcTrigger.runGc();
    // 再次移除所有弱引用可達(dá)對(duì)象
    removeWeaklyReachableReferences();
    if (!gone(reference)) {
      long startDumpHeap = System.nanoTime();
      long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
      // 利用Debug生成Hprof文件
      File heapDumpFile = heapDumper.dumpHeap();
      if (heapDumpFile == RETRY_LATER) {
        // Could not dump the heap.
        return RETRY;
      }
      long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);

      HeapDump heapDump = heapDumpBuilder.heapDumpFile(heapDumpFile).referenceKey(reference.key)
          .referenceName(reference.name)
          .watchDurationMs(watchDurationMs)
          .gcDurationMs(gcDurationMs)
          .heapDumpDurationMs(heapDumpDurationMs)
          .build();

      heapdumpListener.analyze(heapDump);  // 開始分析hprof文件
    }
    return DONE;
  }

  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很重要的方法就是watch方法, 其中參數(shù)watchedReference就是對(duì)應(yīng)的view、activity、fragment對(duì)象。 通過UUID 函數(shù)生成唯一的標(biāo)識(shí)添加到Set<String>集合當(dāng)中。 KeyedWeakReference繼承了WeakReference,關(guān)聯(lián)了watchedReference。當(dāng)進(jìn)弱引用對(duì)象發(fā)生回收的時(shí)候,虛擬機(jī)就會(huì)向該引用添加到與之關(guān)聯(lián)的引用隊(duì)列當(dāng)中。

檢測內(nèi)存是否泄漏的過程也很簡單:首先會(huì)清除所有的弱引用可達(dá)對(duì)象, 判斷watchedReference對(duì)象是否已經(jīng)被回收了, 如果沒有,則手動(dòng)進(jìn)行一個(gè)GC,二次確認(rèn)watchedReference對(duì)象是否被回收,如果沒被回收則dump hprof文件,通知heapdumpListener分析hprof文件

3.6. AndroidWatchExecutor 類
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(@NonNull Retryable retryable) {
   if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
     waitForIdle(retryable, 0);
   } else {
     postWaitForIdle(retryable, 0);
   }
 }

 private void postWaitForIdle(final Retryable retryable, final int failedAttempts) {
   mainHandler.post(new Runnable() {
     @Override public void run() {
       waitForIdle(retryable, failedAttempts);
     }
   });
 }

 private void waitForIdle(final Retryable retryable, final int failedAttempts) {
   // This needs to be called from the main thread.
   Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
     @Override public boolean queueIdle() {
       postToBackgroundWithDelay(retryable, failedAttempts);
       return false;
     }
   });
 }

 private void postToBackgroundWithDelay(final Retryable retryable, final int failedAttempts) {
   long exponentialBackoffFactor = (long) Math.min(Math.pow(2, failedAttempts), maxBackoffFactor);
   long delayMillis = initialDelayMillis * exponentialBackoffFactor;
   // 利用HandlerThread對(duì)象里面的Looper進(jìn)行子線程任務(wù)
   backgroundHandler.postDelayed(new Runnable() {
     @Override public void run() {
       Retryable.Result result = retryable.run();
       if (result == RETRY) {
         postWaitForIdle(retryable, failedAttempts + 1);
       }
     }
   }, delayMillis);
 }
}

WatchExecutor 是一個(gè)線程調(diào)度器。包含了一個(gè)主線程 mainHandler 和后臺(tái)線程backgroundHandler。整個(gè)的邏輯就是當(dāng)主線程空閑的時(shí)候,才回去啟動(dòng)后臺(tái)線程去執(zhí)行Retryable.run方法。

3.7. AndroidHeapDumper 生成hprof文件
  public File dumpHeap() {
    // 生成hprof文件
    File heapDumpFile = leakDirectoryProvider.newHeapDumpFile();

    if (heapDumpFile == RETRY_LATER) {
      return RETRY_LATER;
    }

    FutureResult<Toast> waitingForToast = new FutureResult<>();
    showToast(waitingForToast);

    if (!waitingForToast.wait(5, SECONDS)) {
      Log.d("LeakCanary", "Did not dump heap, too much time waiting for Toast.");
      CanaryLog.d("Did not dump heap, too much time waiting for Toast.");
      return RETRY_LATER;
    }
    // 創(chuàng)建正在dumping通知
    Notification.Builder builder = new Notification.Builder(context)
        .setContentTitle(context.getString(R.string.leak_canary_notification_dumping));
    Notification notification = LeakCanaryInternals.buildNotification(context, builder);
    NotificationManager notificationManager =
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    int notificationId = (int) SystemClock.uptimeMillis();
    notificationManager.notify(notificationId, notification);

    Toast toast = waitingForToast.get();
    try {
      // 系統(tǒng)Debug類提供的方法
      Debug.dumpHprofData(heapDumpFile.getAbsolutePath());
      cancelToast(toast);
      notificationManager.cancel(notificationId);
      return heapDumpFile;
    } catch (Exception e) {
      CanaryLog.d(e, "Could not dump heap");
      // Abort heap dump
      return RETRY_LATER;
    }
  }

  private void showToast(final FutureResult<Toast> waitingForToast) {
    mainHandler.post(new Runnable() {
      @Override public void run() {
        if (resumedActivity == null) {
          waitingForToast.set(null);
          return;
        }
        final Toast toast = new Toast(resumedActivity);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        LayoutInflater inflater = LayoutInflater.from(resumedActivity);
        toast.setView(inflater.inflate(R.layout.leak_canary_heap_dump_toast, null));
        toast.show();
        // Waiting for Idle to make sure Toast gets rendered.
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
          @Override public boolean queueIdle() {
            waitingForToast.set(toast);
            Log.d("LeakCanary", "latch.countDown()");
            return false;
          }
        });
      }
    });
  }

dumpHeap方法利用Debug.dumpHprofData(String filePath)生成hprof文件,同時(shí)會(huì)展示Toast以及通知欄狀態(tài)。如果dump失敗或者Toast展示時(shí)間太長就會(huì)返回RETRY_LATER。

3.8 HeapAnalyzerService 分析hprof文件,找出泄漏路徑
  @Override protected void onHandleIntentInForeground(@Nullable Intent intent) {
    if (intent == null) {
      CanaryLog.d("HeapAnalyzerService received a null intent, ignoring.");
      return;
    }
    String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
    HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);

    HeapAnalyzer heapAnalyzer =
        new HeapAnalyzer(heapDump.excludedRefs, this, heapDump.reachabilityInspectorClasses);

    Log.d("LeakCanary", "leak path:" + heapDump.heapDumpFile.getAbsolutePath());

    AnalysisResult result = heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey,
        heapDump.computeRetainedHeapSize);
    AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
  }

HeapAnalyzer 是hprof文件解析類, 使用了squareup的另外一個(gè)開源庫—Haha。

  public @NonNull AnalysisResult checkForLeak(@NonNull File heapDumpFile,
      @NonNull String referenceKey,
      boolean computeRetainedSize) {
    long analysisStartNanoTime = System.nanoTime();

    Log.d("LeakCanary", "heapDumpFile path:" + heapDumpFile.getAbsolutePath());
    Log.d("LeakCanary", "referenceKey = " + referenceKey);
    if (!heapDumpFile.exists()) {
      Exception exception = new IllegalArgumentException("File does not exist: " + heapDumpFile);
      return failure(exception, since(analysisStartNanoTime));
    }

    // Hprof 文件協(xié)議介紹: https://my.oschina.net/u/217380/blog/1507542
    try {
      listener.onProgressUpdate(READING_HEAP_DUMP_FILE);
      // 把hprof文件映射到內(nèi)存 ByteBuffer[]
      HprofBuffer buffer = new MemoryMappedFileBuffer(heapDumpFile);
      HprofParser parser = new HprofParser(buffer);
      listener.onProgressUpdate(PARSING_HEAP_DUMP);
      // 創(chuàng)建了HprofParser對(duì)象,parse方法解析hprof協(xié)議,生成Snapshot
      Snapshot snapshot = parser.parse();
      listener.onProgressUpdate(DEDUPLICATING_GC_ROOTS);
      // 去除重復(fù)的GC root對(duì)象
      deduplicateGcRoots(snapshot);
      listener.onProgressUpdate(FINDING_LEAKING_REF);
      Instance leakingRef = findLeakingReference(referenceKey, snapshot);

      // 此對(duì)象不存在,表示已經(jīng)被gc清除了,不存在泄露因此返回?zé)o泄漏
      // False alarm, weak reference was cleared in between key check and heap dump.
      if (leakingRef == null) {
        String className = leakingRef.getClassObj().getClassName();
        return noLeak(className, since(analysisStartNanoTime));
      }
      // 此對(duì)象存在, 也不能確認(rèn)它內(nèi)存泄漏了,要檢測此對(duì)象的gc root
      return findLeakTrace(analysisStartNanoTime, snapshot, leakingRef, computeRetainedSize);
    } catch (Throwable e) {
      return failure(e, since(analysisStartNanoTime));
    }
  }
image.png
3.9 DisplayLeakService 生成內(nèi)存泄漏通知欄
  protected final void onHeapAnalyzed(@NonNull AnalyzedHeap analyzedHeap) {
    Log.d("LeakCanary", "[DisplayLeakService]: onHeapAnalyzed");
    HeapDump heapDump = analyzedHeap.heapDump;
    AnalysisResult result = analyzedHeap.result;

    String leakInfo = leakInfo(this, heapDump, result, true);
    CanaryLog.d("%s", leakInfo);

    heapDump = renameHeapdump(heapDump);
    boolean resultSaved = saveResult(heapDump, result);

    String contentTitle;
    if (resultSaved) {
      PendingIntent pendingIntent =
          DisplayLeakActivity.createPendingIntent(this, heapDump.referenceKey);
      if (result.failure != null) {
        contentTitle = "Leak analysis failed";
      } else {
        String className = classSimpleName(result.className);
        if (result.leakFound) {
          if (result.retainedHeapSize == AnalysisResult.RETAINED_HEAP_SKIPPED) {
            if (result.excludedLeak) {
              contentTitle = getString(R.string.leak_canary_leak_excluded, className);
            } else {
              contentTitle = getString(R.string.leak_canary_class_has_leaked, className);
            }
          } else {
            String size = formatShortFileSize(this, result.retainedHeapSize);
            if (result.excludedLeak) {
              contentTitle =
                  getString(R.string.leak_canary_leak_excluded_retaining, className, size);
            } else {
              contentTitle =
                  getString(R.string.leak_canary_class_has_leaked_retaining, className, size);
            }
          }
        } else {
          contentTitle = getString(R.string.leak_canary_class_no_leak, className);
        }
      }
      String contentText = getString(R.string.leak_canary_notification_message);
      showNotification(pendingIntent, contentTitle, contentText);
    } else {
      onAnalysisResultFailure(getString(R.string.leak_canary_could_not_save_text));
    }

    afterDefaultHandling(heapDump, result, leakInfo);
  }
四、LeakCanary不足

雖然 LeakCanary 有諸多優(yōu)點(diǎn),但是它也有做不到的地方,比如說檢測申請大容量內(nèi)存導(dǎo)致的OOM問題、Bitmap內(nèi)存未釋放問題,Service 中的內(nèi)存泄漏可能無法檢測等。

五、延申閱讀

1. Matrix ResourceCanary -- Activity 泄漏及Bitmap冗余檢測
2. Hprof 文件協(xié)議
3. GC那些事兒--Android內(nèi)存優(yōu)化第一彈

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容