有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    关于这个主题的另一篇好文章:
    Java Reference Objects or How I Learned to Stop Worrying and Love OutOfMemoryError,有漂亮的图表

    http://www.kdgregory.com/images/java.refobj/object_life_cycle_with_refobj.gif

    摘录:

    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 a WeakReference but don't create a SoftReference, then an object progresses directly from strongly-reachable to weakly-reachable to finalized to collected. object life-cycle, with reference objects

    记住并非所有对象都附加到引用对象上,这一点也很重要-事实上,很少有对象应该附加到引用对象上
    引用对象是一个间接层:您通过引用对象到达引用对象,显然您不希望在整个代码中使用该间接层
    事实上,大多数程序将使用引用对象访问程序创建的相对较少的对象

    引用和引用

    引用对象在程序代码和其他对象(称为referent)之间提供了一个间接层
    每个引用对象都围绕其引用对象构造,并提供一个get()方法来访问引用对象。创建引用后,不能更改其referent。收集引用对象后,get()方法返回null。应用程序代码、软/弱引用和引用之间的关系

    alt text


    甚至更多的例子:Java Programming: References' Package

    alt text 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.

  2. # 3 楼答案

    有一个非常简单的规则:

    • 强引用对象是像Object a = new Object()这样的标准代码位。只要引用(a,上面)是“可访问的”,引用对象就不是垃圾。因此,任何没有可到达的强引用的东西都可以被视为垃圾

    然后我们来看看非强引用类型:

    • 弱引用的对象可能会在符合GC条件时被JVM收集(并且WeakReference被清除)。对a的弱引用看起来像new WeakReference<Object>(a)。弱引用在需要缓存的情况下非常有用,因为只有在其他地方(例如HttpSessions)可以强访问密钥时,才需要缓存数据
    • 软引用的对象可能会挂在JVM中,直到它完全需要恢复内存。软引用对于缓存非常有用,因为缓存中的值是长期存在的,但在必要时可以收集这些值

    我从来都不太确定幻影