WeakReference

reachable, the following happens:
A set ref of references is determined. ref contains the following elements:
All weak references pointing to obj.
All weak references pointing to objects from which obj is either strongly or softly reachable.
All references in ref are atomically cleared.
All objects formerly being referenced by ref become eligible for finalization.
At some future point, all references in ref will be enqueued with their corresponding reference queues, if any.
Weak references are useful for mappings that should have their entries removed automatically once they are not referenced any more (from outside). The difference between a SoftReference and a WeakReference is the point of time at which the decision is made to clear and enqueue the reference:
A SoftReference should be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory.
A WeakReference may be cleared and enqueued as soon as is known to be weakly-referenced.

(1)WeakReference
   WeakReference實現了一個弱引用,弱引用是三種引用(StrongReference、WeakReference、SoftReference)中的一個。一旦垃圾回收器判定一個對象是是弱獲取(對象可獲取程度分爲五種strongly reachable,softly reachable、weakly reachable、phantomly reachable、unreachable),則下列情況發生:
計算一組引用的ref,ref包括下列元素:
所有指向obj的弱引用
所有指向objects的弱引用,objects是軟獲取對象或者是強獲取對象
在ref中的所有引用被自動刪除
所有以前被ref引用的對象都符合終止條件的對象(become eligible for finalization)
在未來的某個時間,所有的在ref中的引用將被放入合適的引用隊列中
弱引用對那些映射,這些映射中的實體的引用一旦被不存在這些實體將被自動刪除。弱引用和軟引用的區別是清空和將加入排隊的時間點不同:
一個弱引用應該儘可能晚的被清除和加入隊列,那是因爲如果內存不足是vm將是危險的
弱引用對象是一旦知道引用的是弱獲取對象就會被清除和入隊。

 

A SoftReference should be cleared and enqueued as late as possible, that is, in case the VM is in danger of running out of memory.

一個軟引用應該儘可能遲的被清理和入列,因此,在這種情況下虛擬機(VM)就存在內存溢出的風險(危險)。

個人理解:問題在“as late as possible”——始終過遲的清理垃圾,肯定就有內存溢出的風險(危險)。 
------------------------------------
All objects formerly being referenced by ref become eligible for finalization.
所有先前被ref引用的對象都將符合垃圾回收(finalization)的條件。
ref:地址引用,java裏就是指被new創建的對象。
除非是使用JNI,所佔用的內存將不在ref的範圍(Thinking in Java 4th, 120頁)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章