验证使用内部类对象时外部类对象是否被回收

使用 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   给了我一部分的解答,也感谢老师告诉我验证的方法。

(仅供个人参考)

caozhy  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值