This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
A, B, X
Posted by Bill Venners on 03 Jun 1998, 1:50 PM
> Suppose there is object A holding reference to another
> object B's innerclass instance, say X. Now assign B to null.
> Inner classe instance X does not reference any variables of B.
> I thought B should be garbage collected because nobody is
> using this.
> I tested it and found that SUN's JVM doesn't gc object B.
> What's your take on this?
There are two reasons this would happen. First, B wasn't really
unreferenced (I'll explain below). Second, even if B really
was unreferenced, Sun's JVM may not have felt like garbage
collecting B at the moment. JVMs are allowed to be quite
idiosyncratic about when and how they do garbage collection.
Even if you say System.gc(), that just means you are giving
the VM a hint that this would be a good time to do GC, but
the VM is free to ignore your hint entirely if it wants.
But the interesting answer to your question is that instances
of inner classes (in this case X) contain a reference to
each of their enclosing instances (in this case, just B). So
X contained a hidden referenced to B, which was automatically
generated by the Java compiler. Since A referenced X and X
referenced B, B won't get garbage collected.
Inner classes need a reference to an instance of each
of their their enclosing classes
so that the inner classes can invoke instance methods and
fiddle with instance variables on the instances
of their enclosing classes.
For more info on this, check out the "How do inner classes
affect the idea of this in Java code?" section of the Inner