Android 記憶體泄露偵查工具 LeakCanary 的監控原理

來源:互聯網
上載者:User

標籤:

首先回顧一下  java 的幾種 reference:

從jdk 1.2 開始,引用分為 強引用,軟引用、若引用 和虛引用, 其中 軟引用、若引用 和虛引用 和 ReferenceQueue 關聯。


在JDK 1.2以前的版本中,若一個對象不被任何變數引用,那麼程式就無法再使用這個對象。也就是說,只有對象處於可觸及(reachable)狀態,程式才能使用它。從JDK 1.2版本開始,把對象的引用分為4種層級,從而使程式能更加靈活地控制對象的生命週期。這4種層級由高到低依次為:強引用、軟引用、弱引用和虛引用。

1,強引用(Strong Reference, 沒有具體的類來標識強引用,正常的使用的對象引用都是強引用,由vm實現)

強引用是使用最普遍的引用。如果一個對象具有強引用,那記憶體回收行程絕不會回收它。

當記憶體空間不足,Java虛擬機器寧願拋出OutOfMemoryError錯誤,使程式異常終止,也不會靠隨意回收具有強引用的對象來解決記憶體不足的問題。


2,軟引用(SoftReference)

如果一個對象只具有軟引用,則記憶體空間足夠,記憶體回收行程就不會回收它;如果記憶體空間不足了,就會回收這些對象的記憶體。

只要記憶體回收行程沒有回收它,該對象就可以被程式使用。軟引用可用來實現記憶體敏感的快取。

軟引用可以和一個引用隊列(ReferenceQueue)聯合使用,如果軟引用所引用的對象被記憶體回收行程回收,Java虛擬機器就會把這個軟引用加入到與之關聯的引用隊列中。


3,弱引用(WeakReference)

弱引用與軟引用的區別在於:只具有弱引用的對象擁有更短暫的生命週期。

在記憶體回收行程線程掃描它所管轄的記憶體地區的過程中,一旦發現了只具有弱引用的對象,不管當前記憶體空間足夠與否,都會回收它的記憶體。

不過,由於記憶體回收行程是一個優先順序很低的線程,因此不一定會很快發現那些只具有弱引用的對象。

弱引用可以和一個引用隊列(ReferenceQueue)聯合使用,如果弱引用所引用的對象被記憶體回收,Java虛擬機器就會把這個弱引用加入到與之關聯的引用隊列中。


4,虛引用(PhantomReference)

“虛引用”顧名思義,就是形同虛設,與其他幾種引用都不同,虛引用並不會決定對象的生命週期。如果一個對象僅持有虛引用,那麼它就和沒有任何引用一樣,在任何時候都可能被記憶體回收行程回收。

虛引用主要用來跟蹤對象被記憶體回收行程回收的活動。虛引用與軟引用和弱引用的一個區別在於:虛引用必須和引用隊列 (ReferenceQueue)聯合使用

當記憶體回收行程準備回收一個對象時,如果發現它還有虛引用,就會在回收對象的記憶體之前,把這個虛引用加入到與之 關聯的引用隊列中。

ReferenceQueue queue = new ReferenceQueue ();  PhantomReference pr = new PhantomReference (object, queue);

程式可以通過判斷引用隊列中是否已經加入了虛引用,來瞭解被引用的對象是否將要被記憶體回收。如果程式發現某個虛引用已經被加入到引用隊列,那麼就可以在所引用的對象的記憶體被回收之前採取必要的行動。


5,ReferenceQueue是作為 JVM GC與上層Reference對象管理之間的一個訊息傳遞方式, 軟引用、若引用等的入隊操作有vm的gc直接操作


LeakCanary 中的 RefWatcher 就是通過若引用及其隊列來實現監控的:

有兩個很重的結構: retainedKeys 和 queue ,

   retainedKeys 代表沒被gc 回收的對象, 

    而queue中的若引用代表的是被gc 了的對象,通過這兩個結構就可以監控對象是不是被回收了;

retainedKeys 存放了RefWatcher 為每個被監控的對象產生的唯一key;

同時每個被監控對象的若引用(KeyedWeakReference)關聯了 其對應的key 和 queue,這樣對象若被回收,則其對應的若引用會被入隊到queue中;

removeWeaklyReachableReferences(..)所做的就是把存在與 queue 中的若引用的key 從 retainedKeys 中刪除。

  private final Set<String> retainedKeys;  private final ReferenceQueue<Object> 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 回收。


AndroidWatchExecutor:

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 等分析工具找到泄露對象的引用路徑。


參考 :http://blog.csdn.net/lyfi01/article/details/6415726, http://hongjiang.info/java-referencequeue/


Android 記憶體泄露偵查工具 LeakCanary 的監控原理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.