Java嵌套类实例防止外部类的GC

时间:2015-04-13 05:41:19

标签: java oop garbage-collection

假设Outer在某处实例化,过了一段时间没有对它的引用。 inner中对Outer实例的隐式引用是否会阻止GC运行,或者它是否为#34;特殊的"参考

public class Outer {
    private class Inner extends Something {}

    private Inner inner = new Inner();
}

1 个答案:

答案 0 :(得分:3)

如果无法从GC根目录访问Outer的实例,则示例代码中对Inner实例的引用不会阻止垃圾收集器释放内存Outer用过的。

考虑这个图:

Stack of main thread           public static void main(String[] args) {
         |                       Outer outer = new Outer();
         v                     
       Outer<--\
         |\    |
         v \---/
       Inner 

Stack of main thread               outer = new Outer();
         |
         v          
       Outer<--\
         |\ new|
         v \---/
       Inner 

       Outer<--\                   // a reference to the Outer from the Inner
         |\ old|                   // doesn't change the fact that the Outer
         v \---/                   // can't be reached from a GC root.
       Inner                       // Thus the old Outer is eligible for collection (dead)