例如用下面的代碼,Java垃圾收集時,有沒有參考對象
class Dog {
Dog parent;
Dog (Dog parent) {
this.parent = parent;
}
Dog makeDog (Dog dog) {
return new Dog(new Dog(new Dog(dog)));
}
}
public class test {
public static void main(String[] args) {
Dog dog = new Dog(null);
dog = dog.makeDog(dog);
Dog anotherDog = new Dog(dog);
/*
* many lines of code
*/
if (anotherDog.parent.parent.parent.parent.parent == null) {
System.out.println("null");
}
}
}
這是程序保證打印空?
我的大部分程序都是用C編寫的,這就是我建立鏈表,樹,圖等等的方式。但我真的不確定Java垃圾收集器如何處理這些代碼,所以在真正的程序中,我選擇將引用存儲在其他地方,以便GC可以知道這些對象確實不是垃圾。
任何幫助,歡迎。
爲什麼GC會認爲它們是垃圾?每條狗都可以從主線程堆棧中變量anotherDog的一系列引用中訪問。 – 2014-10-05 15:45:46
如果我添加'dog = null',該怎麼辦? – xiver77 2014-10-05 15:56:29
每條狗仍然可以從主線程堆棧中變量anotherDog的引用鏈中訪問。 – 2014-10-05 15:58:35