WeakReference,SoftReference 和 PhatomRefere

系统 1496 0

前几天发了一篇关于垃圾收集的帖子,自己也不是这方面的专家,所以肯定有很多问题和错误,也请大家多多包涵和指教。

今天再进一步谈一下这个几个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】:

WeakReference,SoftReference 和 PhatomReference 浅析

上面这段代码演示了几种引用的特性:

  • PhantomReference 总是返回null
  • 垃圾收集之后 PhantomReference WeakReference 都进去了queue,而 SoftReference 没有。证明 SoftReference 生命周期更长。

下面这个例子来自《Thinking in Java》第四版,稍作修改:

这个例子比较有意思,每次执行,结果都会有一些差异。至于为什么,我也在研究之中,欢迎大家指教!

参考:

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

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

WeakReference,SoftReference 和 PhatomReference 浅析


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论