WeakReference,SoftReference 和 PhatomReference 淺析

前幾天發了一篇關於垃圾收集的帖子,自己也不是這方面的專家,所以肯定有很多問題和錯誤,也請大家多多包涵和指教。

今天再進一步談一下這個幾個Reference吧。老實說,這幾個名詞我也是最近才聽說,平時也沒有實際使用過,但是確實在java 1.2就存在的,看來真的是學無止境啊。

 

  • softly reachable:The object is the referent of a SoftReference. The garbage collector will attempt to preserve the object as long as possible, but will collect it before throwing an OutOfMemoryError.
  • weakly reachable:The object is the referent of a WeakReference, and there are no strong or soft references to it. The garbage collector is free to collect the object at any time, with no attempt to preserve it.
  • phantom reachable:The object is the referent of a PhantomReference, and there are no strong, soft, or weak references to it. This reference type differs from the other two in that it isn't meant to be used to access the object, but as a signal that the object has already been finalized, and the garbage collector is ready to reclaim its memory.

 

在《Thinking in Java》第四版是如此描述:In the order of SoftReference, WeakReference, and PhantomReference, each one is "weaker" than the last and corresponds to a different level of reachability. Soft references are for implementing memory-sensitive caches. Weak references are for implementing "canonicalizing mappings"—where instances of objects can be simultaneously used in multiple places in a program, to save storage—that do not prevent their keys (or values) from being reclaimed. Phantom references are for scheduling pre-mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism.

 

在引入了這幾個引用之後,對象的生命週期【1】:

 

上面這段代碼演示了幾種引用的特性:

  • PhantomReference總是返回null
  • 垃圾收集之後PhantomReferenceWeakReference都進去了queue,而SoftReference沒有。證明SoftReference生命週期更長。

下面這個例子來自《Thinking in Java》第四版,稍作修改:

 

這個例子比較有意思,每次執行,結果都會有一些差異。至於爲什麼,我也在研究之中,歡迎大家指教!

 

參考:

【1】http://www.kdgregory.com/index.php?page=java.refobj

【2】http://improving.iteye.com/blog/436311

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章