书上有一段话:
Q: Does unreachable mean when there are no more references to the object?
A: No, but that is a common misunderstanding of garbage collection. You might think that the garbage collector keeps count of how many references there are to an object and then frees the object when the reference count is zero. However, it is easy to come up with a situation in which two objects need to be garbage collected, but each object has a reference to the other. If reference counting was being used, these two objects would never be freed.翻译过来大概是说:
问:当对象没有引用指向它时,就是unreachable吗?
答:不是,但这是关于垃圾回收的一个常见误解。你可能以为垃圾回收器会记录一个对象有多少个引用,当引用数为0时,就清理掉那个对象。但是,有一种很容易遇到的情况是,有2个对象需要被垃圾回收,但他们各自有一个指向对方的引用。如果使用引用数的话,这两个对象就永远不会被清理掉。这里的“2个对象各自有一个指向对方的引用”到底是怎样一种情况呢?感觉这句话特别抽象,很难理解,请问哪位大侠可以给个实例?另外,如果真的存在这种情况,那他们到底可不可以被垃圾回收呢?

解决方案 »

  1.   


    public class A {
        A obj;
        public void setA(A a) {
            obj = a;
        }
        
        public static void main(String[] args) {
            A o1 = new A();
            A o2 = new A();
            o1.setA(o2);
            o2.setA(o1);
        }
    }
      

  2.   

    多谢1楼的代码和2楼的回复,可是根据书上的意思,好像是说他们还是有可能被回收的啊~
    回3楼的:Java in 60 minutes a day,一个新手入门书
      

  3.   


    书我没看过哇 肯定是不会被回收的一个类A里面 含有另一个类B的实例  
    一个类B里面 含有另一个类A的实例这样 就是 each object has a reference to the other
    所以  reference counting was being used which means it would not be zero.
    Thus, these two objects would never be freed.
      

  4.   

    原始的GC有的使用引用计数器(就是英文文中介绍的),这种情况不会被回收。而现在的GC似乎使用了从某个根节点出发,能否访问到这个对象。
      

  5.   

    终于理解了,这两个对象虽然有相互的引用,但是他们两个是无法使用的,因为没有外部引用指向其中任何一个对象,原来这就是unreachable的含义多谢大家
      

  6.   

    其实不同的jvm有不同的垃圾回收机制,究竟会不会回收,什么时候,不能一概而论.
      

  7.   

    测试一下不就知道了public class O {
    private String name;
    public O(String name) {
    this.name = name;
    }
    public O o = null;
    public void setReference(O another) {
    this.o = another;
    another.o = this;
    }
    public void finalize() throws Throwable {
    System.out.println(this.name + " 被回收了!");  // 对象被回收时,会输出这个
    super.finalize();
    }
    public static void main(String[] args) { new O("o1").setReference(new O("o2")); // new 两个对象,并让其互相引用

    System.gc(); // 呼叫几次垃圾回收器, 看它收是不收
    System.gc();
    System.gc();
    System.gc();
    System.gc(); }
    }