简体   繁体   English

有资格进行垃圾收集吗?

[英]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 ? 那么,一旦引用设置为null,otr引用的对象是否有资格进行垃圾回收?

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. 如果查看字节码,则会发现Inner保留了对Outer的隐藏引用,该引用是Java编译器自动生成的。

So as long as oi can be referenced, otr can be referenced as well. 因此,只要oi可以被引用, otr也可以被引用。

Now you might think that an optimization step could get rid the hidden reference to Outer since Inner never uses it. 现在您可能会认为,优化步骤可以摆脱对Outer的隐藏引用,因为Inner从未使用过。 But someone could extend Inner and try to access Outer from there, so the compiler can't make such assumptions. 但是有人可以扩展Inner并尝试从那里访问Outer ,因此编译器无法做出这样的假设。

No, the object created in (1) cannot get garbage collected. 不,在(1)中创建的对象无法收集垃圾。

The inner class instance created in (2) holds reference to object (1) in order to get access to it's fields and methods. 在(2)中创建的内部类实例保留对对象(1)的引用,以便访问其字段和方法。

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). 在第(3)行中删除对对象(1)的直接引用不会使对象(1)可以进行垃圾回收,因为内部类实例(2)仍在(内部)使用对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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