Reputation: 1233
I know that an instance of an inner class must bind to an instance of the wrapper class and this lead me to question what happens to a wrapper class instance, when there is no reference to it but when there is still a reference to a bound instance.
So, is object referenced by otr eligible for garbage collection once the reference is set to null ?
class Outer
{
class Inner
{
}
}
class Test{
public static void main(String []args){
Outer otr = new Outer() ; // (1)
Outer.Inner oi = otr.new Inner() ; // (2)
otr = null ; // (3)
// more complicated code
}
}
Upvotes: 1
Views: 140
Reputation: 203
No, the object created in (1) cannot get garbage collected.
The inner class instance created in (2) holds reference to object (1) in order to get access to it's fields and methods.
Removing direct reference to object (1) in line (3) is not going to make object (1) eligible for garbage collection, because object is still used (internally) by inner class instance (2).
Upvotes: 2
Reputation: 328556
If you look at the byte code, then you'll see that Inner
keeps a hidden reference to Outer
which is automatically generated by the Java compiler.
So as long as oi
can be referenced, otr
can be referenced as well.
Now you might think that an optimization step could get rid the hidden reference to Outer
since Inner
never uses it. But someone could extend Inner
and try to access Outer
from there, so the compiler can't make such assumptions.
Upvotes: 3
Reputation: 6306
As you stated the (non-static) inner class has an (implicit) reference to the outer class instance used to create it. Therefore the instance of the outer class cannot be garbage collected until the instance of the inner class is no longer (strongly) referenced.
Upvotes: 4