Can someone explain the difference between Strong, Soft, Weak and Phantom references and the usage of it?
我一直在试图理解不同参考文献之间的差异,但这一理论并没有激发出任何想法让我将其形象化。
有人能简要解释一下不同的参考资料吗?
每种方法都有一个更好的例子。
关于这个主题的另一篇好文章:Java参考对象< Sub >或我如何学会用简单的图表来防止烦恼和爱
提取物:
As you might guess, adding three new optional states to the object life-cycle diagram makes for a mess.
Although the documentation indicates a logical progression from strongly reachable through soft, weak, and phantom, to reclaimed, the actual progression depends on what reference objects your program creates.
If you create aWeakReference but don't create aSoftReference , then an object progresses directly from strongly-reachable to weakly-reachable to finalized to collected. object life-cycle, with reference objects
同样重要的是要记住,并不是所有的对象都与引用对象相关联——事实上,它们应该很少。引用对象是一个间接层:您通过引用对象到达引用对象,显然您不希望在整个代码中使用该间接层。实际上,大多数程序将使用引用对象来访问程序创建的相对较少的对象。
参考文献和参考文献
引用对象提供了程序代码和其他对象(称为引用)之间的间接层。每个引用对象围绕其引用构造,并提供一个get()方法来访问引用。创建引用后,不能更改其引用。一旦收集了引用,get()方法将返回空值。应用程序代码、软/弱引用和引用之间的关系
更多的例子:Java编程:引用的包
alt文本http://www.pabrantes.net/blog/space/start/2007-09-16/1/referencetypes.png
Case 1: This is the regular case where Object is said to be strongly reachable.
Case 2: There are two paths to Object, so the strongest one is chosen, which is the one with the strong reference hence the object is strongly reachable.
Case 3: Once again there are two paths to the Object, the strongest one is the Weak Reference (since the other one is a Phantom Reference), so the object is said to be weakly reachable.
Case 4: There is only one path and the weakest link is a weak reference, so the object is weakly reachable.
Case 5: Only one path and the weakest link is the phantom reference hence the object is phantomly reachable.
Case 6: There are now two paths and the strongest path is the one with a soft reference, so the object is now said to be softly reachable.
一篇解释这些引用类型的文章(包括示例):http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html
有一个非常简单的规则:
- 强引用对象是标准的代码位,如
Object a = new Object() 。只要引用(上面的a 是"可访问的",被引用对象就不会是垃圾。因此,任何没有可到达的强引用的东西都可以被视为垃圾。
然后我们来看看非强引用类型:
- 弱引用对象可能会在它们符合GC(并且清除
WeakReference )的条件时被JVM收集。弱引用a 看起来像new WeakReference 。弱引用在需要缓存的情况下很有用,只有当密钥在其他地方(如httpsessions)具有强可访问性时,才需要数据。 - 软引用对象可能会挂在JVM中,直到它绝对需要恢复内存为止。软引用对于值长期存在但在必要时可以收集的缓存很有用。
我对幻影一点也不太确定!