2010-01-12 119 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。