I have two classes
Class A
{
//constructor
}
Class B
{
private A a;
public B()
{
a = new A();
}
}
Suppose I u
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)
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.
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
.
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
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.