對於Reference
類你們可能會比較陌生,平時用的也比較少,對他的印象可能僅停在面試的時候查看引用相關的知識點;但在仔細查看源碼後發現Reference
仍是很是實用的,平時咱們使用的類都是強引用的,它的回收徹底依賴於 GC;可是對於有些類咱們想要本身控制的時候就比較麻煩,好比我想在內存還足夠的時候就保留,不夠的時候就回收,這時使用Reference
就可以十分靈活的控制類的存亡了。java
/** * Abstract base class for reference objects. This class defines the * operations common to all reference objects. Because reference objects are * implemented in close cooperation with the garbage collector, this class may * not be subclassed directly. * * @author Mark Reinhold * @since 1.2 */ public abstract class Reference<T> {}
從註釋和類圖中能夠清楚的看到:面試
Reference
類是直接配合GC
操做的,因此不能直接子類化,可是能夠繼承Reference
的子類;Reference
類定義了子類的主要邏輯,因此在SoftReference
、WeakReference
和PhantomReference
中幾乎徹底複用了Reference
的邏輯;如圖所示,Reference 的處理流程至關於事件處理算法
在 Reference 的生命週期裏面,一共有四個狀態:框架
上面咱們提到當引用強弱關係發生變化的時候,他的狀態會發生改變,那麼這個強弱關係是如何判斷的呢?
熟悉 JVM 的同窗應該知道判斷對象是否存活的算法大體有兩種;ide
上圖僅表示了,強引用的回收,當加入了軟引用,弱引用和虛應用以後:函數
已上圖爲例:oop
private T referent; /* Treated specially by GC */ volatile ReferenceQueue<? super T> queue; volatile Reference next; transient private Reference<T> discovered; /* used by VM */ private static Reference<Object> pending = null; Reference(T referent) { this(referent, null); } Reference(T referent, ReferenceQueue<? super T> queue) { this.referent = referent; this.queue = (queue == null) ? ReferenceQueue.NULL : queue; }
ReferenceQueue
的名字裏面有隊列,可是它的內部卻沒有包含任何隊列和鏈表的結構;他的內部封裝了單向鏈表的添加,刪除和遍歷等操做,實際做用至關於事件監聽器;static { ThreadGroup tg = Thread.currentThread().getThreadGroup(); for (ThreadGroup tgn = tg; tgn != null; tg = tgn, tgn = tg.getParent()); Thread handler = new ReferenceHandler(tg, "Reference Handler"); /* If there were a special system-only priority greater than * MAX_PRIORITY, it would be used here */ handler.setPriority(Thread.MAX_PRIORITY); handler.setDaemon(true); handler.start(); // provide access in SharedSecrets SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { @Override public boolean tryHandlePendingReference() { return tryHandlePending(false); } }); }
能夠看到在初始化的時候首先獲得了層級最高的線程組即 System線程組,而後在裏面加入了一個名爲 「Reference Handler」 的 優先級最高 的 ReferenceHandler 線程;
接下來的一段代碼是用於保證 JVM 在拋出 OOM 以前,原子性的清除非強引用的全部引用,若是空間仍然不足纔會拋出 OOM;其中 SharedSecrets
用於訪問類的私有變量,於反射不一樣的是,它不會建立新的對象;好比:this
package java.nio; // Class Bits static void reserveMemory(long size, int cap) { ... // optimist! if (tryReserveMemory(size, cap)) { return; } // 走到這裏就說明空間已經不足了 final JavaLangRefAccess jlra = SharedSecrets.getJavaLangRefAccess(); // retry while helping enqueue pending Reference objects // which includes executing pending Cleaner(s) which includes // Cleaner(s) that free direct buffer memory while (jlra.tryHandlePendingReference()) { if (tryReserveMemory(size, cap)) { return; } } ... }
有關 「Reference Handler」 的線程信息可使用jstack [] <pid>
抓取棧信息查看:spa
"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007fa1ac154170 nid=0x32a7 in Object.wait() [0x00007fa19661f000] java.lang.Thread.State: WAITING (on object monitor) at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:502) at java.lang.ref.Reference.tryHandlePending(Reference.java:191) - locked <0x00000006c7e79bc0> (a java.lang.ref.Reference$Lock) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)
private static class ReferenceHandler extends Thread { private static void ensureClassInitialized(Class<?> clazz) { try { Class.forName(clazz.getName(), true, clazz.getClassLoader()); } catch (ClassNotFoundException e) { throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); } } static { // pre-load and initialize InterruptedException and Cleaner classes // so that we don't get into trouble later in the run loop if there's // memory shortage while loading/initializing them lazily. ensureClassInitialized(InterruptedException.class); ensureClassInitialized(Cleaner.class); } ReferenceHandler(ThreadGroup g, String name) { super(g, name); } public void run() { while (true) { tryHandlePending(true); } } }
能夠看到這個線程只作了一件很簡單的事情:線程
InterruptedException
和Cleaner
已經加載,關於Cleaner
就是一個虛引用的實際應用,後面還會詳細講到;tryHandlePending
;/** * Try handle pending {@link Reference} if there is one.<p> * Return {@code true} as a hint that there might be another * {@link Reference} pending or {@code false} when there are no more pending * {@link Reference}s at the moment and the program can do some other * useful work instead of looping. * * @param waitForNotify if {@code true} and there was no pending * {@link Reference}, wait until notified from VM * or interrupted; if {@code false}, return immediately * when there is no pending {@link Reference}. * @return {@code true} if there was a {@link Reference} pending and it * was processed, or we waited for notification and either got it * or thread was interrupted before being notified; * {@code false} otherwise. */ static boolean tryHandlePending(boolean waitForNotify) { Reference<Object> r; Cleaner c; try { synchronized (lock) { if (pending != null) { r = pending; // 'instanceof' might throw OutOfMemoryError sometimes // so do this before un-linking 'r' from the 'pending' chain... c = r instanceof Cleaner ? (Cleaner) r : null; // unlink 'r' from 'pending' chain pending = r.discovered; r.discovered = null; } else { // The waiting on the lock may cause an OutOfMemoryError // because it may try to allocate exception objects. if (waitForNotify) { lock.wait(); } // retry if waited return waitForNotify; } } } catch (OutOfMemoryError x) { // Give other threads CPU time so they hopefully drop some live references // and GC reclaims some space. // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above // persistently throws OOME for some time... Thread.yield(); // retry return true; } catch (InterruptedException x) { // retry return true; } // Fast path for cleaners if (c != null) { c.clean(); return true; } ReferenceQueue<? super Object> q = r.queue; if (q != ReferenceQueue.NULL) q.enqueue(r); return true; }
這個方法主要完成了discovered -> pending -> enqueued
的整個入隊註冊流程;值得注意的是雖然Cleaner
是虛引用,可是它並不會入隊,而是直接執行clean
操做,也就意味着在使用Cleaner
的時候不須要在起一個線程監聽ReferenceQueue
了;
static ReferenceQueue<Object> NULL = new Null<>(); // 用於標記是否已經入隊,防止重複入隊 static ReferenceQueue<Object> ENQUEUED = new Null<>(); private volatile Reference<? extends T> head = null; private long queueLength = 0; // reference入隊操做 boolean enqueue(Reference<? extends T> r) { /* Called only by Reference class */ // poll 移除reference鏈表頭元素 public Reference<? extends T> poll() { } // 移除reference鏈表下一個元素 public Reference<? extends T> remove(long timeout) { } public Reference<? extends T> remove() throws InterruptedException { } void forEach(Consumer<? super Reference<? extends T>> action) { }
從上面的代碼也能夠看出ReferenceQueue
的確沒有包含任何鏈表或者隊列的結構,可是封裝了單向的鏈表的操做;