SCJP Mock Question: How many objects are eligible for garbage collection?

I was asked a question (on this site http://scjptest.com/): How many objects are eligible for garbage collection in this code sample at the line // 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
    }
}

The correct answer is: “The objects referenced by a and b are eligible for garbage collection.”. But why? they contain loop references to each other, they are accessible to each other.

Thank you!

Answer

they contain loop references to each other, they are accessible to each other.

Yes, but they aren’t anymore accessible from anywhere else, so they can’t be seen and used in the program anymore.

Early GCs had problems collecting such self-referencing object groups but with modern generational collectors it is a solved problem.

In brief, the GC can walk through the web of references from the known static and stack objects, and either

  • copy all objects found to a new memory pool, automatically leaving behind any “dead” objects (this is the “young generation” strategy), or
  • mark all objects found, so that once the whole web of references is walked traversed, it can delete all unmarked objects (this is the “old/tenured generation” strategy).

Leave a Reply

Your email address will not be published. Required fields are marked *