@Test public void strongReference() { Object referent = new Object(); /** * 經過賦值建立 StrongReference */ Object strongReference = referent; assertSame(referent, strongReference); referent = null; System.gc(); /** * StrongReference 在 GC 後不會被回收 */ assertNotNull(strongReference); }
2. WeakReference & WeakHashMap
WeakReference, 顧名思義, 是一個弱引用, 當所引用的對象在 JVM 內再也不有強引用時, GC 後 weak reference 將會被自動回收 html
@Test public void weakReference() { Object referent = new Object(); WeakReference<Object> weakRerference = new WeakReference<Object>(referent); assertSame(referent, weakRerference.get()); referent = null; System.gc(); /** * 一旦沒有指向 referent 的強引用, weak reference 在 GC 後會被自動回收 */ assertNull(weakRerference.get()); }WeakHashMap 使用 WeakReference 做爲 key, 一旦沒有指向 key 的強引用, WeakHashMap 在 GC 後將自動刪除相關的 entry
@Test public void weakHashMap() throws InterruptedException { Map<Object, Object> weakHashMap = new WeakHashMap<Object, Object>(); Object key = new Object(); Object value = new Object(); weakHashMap.put(key, value); assertTrue(weakHashMap.containsValue(value)); key = null; System.gc(); /** * 等待無效 entries 進入 ReferenceQueue 以便下一次調用 getTable 時被清理 */ Thread.sleep(1000); /** * 一旦沒有指向 key 的強引用, WeakHashMap 在 GC 後將自動刪除相關的 entry */ assertFalse(weakHashMap.containsValue(value)); }3. SoftReference
@Test public void softReference() { Object referent = new Object(); SoftReference<Object> softRerference = new SoftReference<Object>(referent); assertNotNull(softRerference.get()); referent = null; System.gc(); /** * soft references 只有在 jvm OutOfMemory 以前纔會被回收, 因此它很是適合緩存應用 */ assertNotNull(softRerference.get()); }4. PhantomReference
@Test public void phantomReferenceAlwaysNull() { Object referent = new Object(); PhantomReference<Object> phantomReference = new PhantomReference<Object>(referent, new ReferenceQueue<Object>()); /** * phantom reference 的 get 方法永遠返回 null */ assertNull(phantomReference.get()); }諸位可能要問, 一個永遠返回 null 的 reference 要來何用, 請注意構造 PhantomReference 時的第二個參數 ReferenceQueue(事實上 WeakReference & SoftReference 也能夠有這個參數),
@Test public void referenceQueue() throws InterruptedException { Object referent = new Object(); ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>(); WeakReference<Object> weakReference = new WeakReference<Object>(referent, referenceQueue); assertFalse(weakReference.isEnqueued()); Reference<? extends Object> polled = referenceQueue.poll(); assertNull(polled); referent = null; System.gc(); assertTrue(weakReference.isEnqueued()); Reference<? extends Object> removed = referenceQueue.remove(); assertNotNull(removed); }6. PhantomReference vs WeakReference
taken from http://mindprod.com/jgloss/phantom.html java
11 緩存