2010-01-12 189 views
5

我在SCJP準備網站上經歷過這個問題。 答案A如何正確?java垃圾回收

對於由a,b,aa引用的對象,在標有「//某些代碼在此處出現 」這一行的情況如何?

class A { 
    private B b; 
    public A() { 
     this.b = new B(this); 
    } 
} 

class B { 
    private A a; 
    public B(A a) { 
     this.a = a; 
    } 
} 

public class Test { 
    public static void main(String args[]) { 
     A aa = new A(); 
     aa = null; 
     // some code goes here 
    } 
} 


A) The objects referenced by a and b are eligible for garbage collection. 
B) None of these objects are eligible for garbage collection. 
C) Only the object referenced by "a" is eligible for garbage collection. 
D) Only the object referenced by "b" is eligible for garbage collection. 
E) Only the object referenced by "aa" is eligible for garbage collection. 

答案:A

回答

8

Java不只是使用一個簡單的引用計數的垃圾收集器。

當JVM執行完整的GC運行時,它遍歷整個對象圖,標記它找到的每個項目。任何未標記的項目都有資格進行清理。

由於ab都不可以從您的主代碼到達,所以它們不會被標記,因此有資格進行清理。

2

好吧,對於不可垃圾收集的東西,從堆棧的任何地方到達它都是不可能的。考慮到那時棧只有aa和單個字符串數組(args)的空值,所以沒有辦法到達a或b。