2014-10-05 60 views
0

例如用下面的代碼,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可以知道這些對象確實不是垃圾。

任何幫助,歡迎。

+2

爲什麼GC會認爲它們是垃圾?每條狗都可以從主線程堆棧中變量anotherDog的一系列引用中訪問。 – 2014-10-05 15:45:46

+0

如果我添加'dog = null',該怎麼辦? – xiver77 2014-10-05 15:56:29

+1

每條狗仍然可以從主線程堆棧中變量anotherDog的引用鏈中訪問。 – 2014-10-05 15:58:35

回答

1

只要通過GC根(線程堆棧或靜態變量)的強引用鏈訪問一個對象,它就不會被垃圾回收。不管多麼複雜的路徑到目標是無關緊要的。

+1

這是不正確的。 'Foo foo = new Foo();酒吧酒吧=新酒吧(); bar.setFoo(FOO); foo.setBar(巴); foo = null; bar = null;'你真的認爲bar和foo不符合GC的條件嗎?然而,酒吧和富都仍然有一個參考。 – 2014-10-05 15:48:09

+1

我認爲你需要添加「GC根源的強大參考路徑」。 – 2014-10-05 15:50:58

+0

@JBNizet在你的例子中,你會說*你有沒有任何引用foo或bar?這就是我的理解,儘管可以更清楚地說明。 – maaartinus 2014-10-05 16:24:17