Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java garbage collection

I was going through this question on an SCJP preparation site . How answer A is correct?

What is true about objects referenced by a, b, aa at the line labeled "// 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.

Answer: A

like image 324
shashwat Avatar asked Jan 12 '10 01:01

shashwat


2 Answers

Java doesn't only use a simple reference-counting garbage collector.

When the JVM does a full GC run, it walks the entire object graph, marking each item it finds. Any items that aren't marked are eligible for cleanup.

Since neither a nor b are reachable from your main code anymore, they won't be marked and are thus eligible for cleanup.

like image 185
Anon. Avatar answered Sep 30 '22 19:09

Anon.


well, for something to not be garbage collectable, it has to be impossible to reach it from anywhere on the stack. Considering that the stack at that point only has a null value for aa and a single string array (args) there is no way to get to a or b.

like image 39
tster Avatar answered Sep 30 '22 18:09

tster