Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collection of Composed Objects

I have two classes

Class A
{
    //constructor
}

Class B
{
    private A a;

    public B()
    {
        a = new A();
    }
}

Suppose I use an object of B [say b] in my code and after I end up using it, I set it to null. I know that the object of B is now available for garbage collection.

I know that after setting b to null, it will be immediately eligible for garbage collection? But what about the object of type A? Will it be available for garbage collection immediately after I set B to null? Or will it be eligible for garbage collection after B is garbage collected?

Theoretically, until B is garbage collected, a still has a reference to it? So will the SUN JVM compiler detect this immediately after setting b = null;

like image 901
Nik Avatar asked May 13 '11 13:05

Nik


1 Answers

The GC is smart enough to follow paths in graphs of objects in order to check if the existing references to some object are reachable. It can even detect cycles (like, in your case, if b held a reference to a and a held a reference to b.

like image 94
Costi Ciudatu Avatar answered Oct 20 '22 12:10

Costi Ciudatu