java垃圾回收

sha*_*wat 5 java garbage-collection

我在SCJP准备网站上经历了这个问题.答案A如何正确?

a,b,aa在标有"// some code goes here"的行引用的对象的真实情况是什么?

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.
Run Code Online (Sandbox Code Playgroud)

答案:A

Ano*_*on. 8

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

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

由于既没有a,也不b是从你的主代码到达了,他们不会被标记,并因此有资格进行清理.