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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值