Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 446
vmg Avatar asked Feb 03 '26 13:02

vmg


2 Answers

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).
like image 179
Péter Török Avatar answered Feb 06 '26 03:02

Péter Török


That's because java has a generational garbage collector so it can collect groups of objects that have references between them, but not from the main application.

There is a more in depth explanation here.

As far as I remember (and I might be wrong) this wasn't the case with old versions of java (such as java 1.2), in which the cyclic dependencies had to be cleared manually in order for the GC to collect them.

like image 29
Augusto Avatar answered Feb 06 '26 04:02

Augusto