java垃圾回收

时间:2010-01-12 01:56:29

标签: java garbage-collection

我在SCJP准备网站上浏览了这个问题。 答案A的答案是否正确?

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

2 个答案:

答案 0 :(得分:8)

Java不仅使用简单的引用计数垃圾收集器。

当JVM执行完整的GC运行时,它会遍历整个对象图,标记它找到的每个项目。任何未标记的项目都有资格进行清理。

由于您的主代码不再可以访问ab,因此它们不会被标记,因此有资格进行清理。

答案 1 :(得分:2)

好吧,对于无法收集垃圾的东西,必须无法从堆栈的任何位置到达它。考虑到该点的堆栈只有aa的空值和单个字符串数组(args),没有办法到达a或b。