使用 Outer.Inner inner = new Outer().new Inner()创建对象时,
Inner类中没有使用Outer中的属性和方法时
外部类对象是否会被jvm的垃圾回收机制回收(可达性分析中没有人连接着外部类对象,但有人连接着内部类对象)
public class TestDemo1 {
private int age = 5;
public static void main(String[] args) throws InterruptedException {
Outer.inner inner = new Outer().new inner();
// for (int i = 0; i < 2; i++) {
// Outer.inner inner = new Outer().new inner();
// System.gc();
// System.gc();
// Thread.sleep(1000);
//
// new Outer().new inner();
// System.gc();
// System.gc();
// Thread.sleep(1000);
// }
while(true) {
System.gc();
}
}
}
public class Outer {
@Override
protected void finalize() throws Throwable {
System.out.println("外部类对象被回收了");
Thread.sleep(1000);
super.finalize();
}
public class inner {
@Override
protected void finalize() throws Throwable {
System.out.println("内部类对象被回收了");
Thread.sleep(1000);
super.finalize();
}
}
}
外部类对象没有被回收
更改Outer.inner inner = new Outer().new inner();为 new Outer().new inner();
运行后提示
外部类对象被回收了
内部类对象被回收了
验证完成。
虽然表面没有任何变量与外部类变量产生了连接,但是jvm仍然认为inner对象与其有着联系,导致没有被jvm进行回收。感谢
caozhy 给了我一部分的解答,也感谢老师告诉我验证的方法。
(仅供个人参考)