Garbage collection of Composed Objects

2020-03-03 05:12发布

问题:

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;

回答1:

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.



回答2:

Once there are no hard references to b there is no way to reach its reference to a, so both are eligible for garbage collection as far as I know.



回答3:

Generally, you shouldn't care. It's not reachable, and you should let the garbage collection worry about the rest. Since it becomes unreachable, it should be eligeble for collection immediately.



回答4:

There are also some flags you can use when running a Java program (at least with the Sun JVM) that will give some debugging information about what goes on during garbage collection. Try the -verbose:gc option.

http://download.oracle.com/javase/6/docs/technotes/tools/solaris/java.html



回答5:

Object A will also become eligible garbage collection as soon as you set ObjectB to null (* condition is ObjectA is not referred by any other live object). This condition is known as "Island of Isolation".

Here is a nice explanation of this situation. (Here is one more explanation from SCJP book)