简体   繁体   中英

Eligible for garbage collection?

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
    }
}

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM