书上有一段话:
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个对象各自有一个指向对方的引用”到底是怎样一种情况呢?感觉这句话特别抽象,很难理解,请问哪位大侠可以给个实例?另外,如果真的存在这种情况,那他们到底可不可以被垃圾回收呢?
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个对象各自有一个指向对方的引用”到底是怎样一种情况呢?感觉这句话特别抽象,很难理解,请问哪位大侠可以给个实例?另外,如果真的存在这种情况,那他们到底可不可以被垃圾回收呢?
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);
}
}
回3楼的:Java in 60 minutes a day,一个新手入门书
书我没看过哇 肯定是不会被回收的一个类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.
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(); }
}