finalize()方法调用的时机

【示例一】

package com.jjyy.basic;
/**
 * finalize方法会在什么时间执行?
 * 
 * @author jiangyu 2015年9月9日
 *
 */
public class FinalizeDemo {
	public static void main(String[] args) {
		Demo demo = new Demo();
		System.out.println("begin to set demo to null");
		demo = null;
		System.out.println("demo was set to null");
	}
}

class Demo{

	@Override
	protected void finalize() throws Throwable {
		System.out.println("Demo finalized");
		super.finalize();
	}
}
/*
结果为:
begin to set demo to null
demo was set to null

注意:finalize()不一定会在将引用设置为null的时候
*/

从示例一的结果来看,并没有在将引用置为null的时候调用了finalize()方法,所以结论为:

finalize()方法根本没有被执行,看一下java中对finalize方法的定义:Called by the garbage collector on an object when garbage collection determines that there are no

 more references to the object.。当垃圾回收确认没有指向对象的引用时,执行回收。而上面的代码新建的对象Demo的唯一引用d已经被释放,而确有执行Demo类的finalize方

法,唯一的原因只能是gc并没有执行,gc只有在JVM内存不足的时候才会自动执行。

【示例二】
package com.jjyy.basic;
/**
 * 程序员手动的控制gc()的运行时机
 * 
 * @author jiangyu 2015年9月9日
 *
 */
public class FinalizedGCDemo {
	public static void main(String[] args) {
		DemoGC demoGC = new DemoGC();
		System.out.println("begin to set demoGC to null");
		demoGC = null;
		System.out.println("demoGC was set null");
		System.out.println("begin to run gc");
		System.gc();
		System.out.println("gc was runed ");
	}
}

class DemoGC{

	@Override
	protected void finalize() throws Throwable {
		System.out.println("Demo finalized");
		super.finalize();
	}
}
/*
结果为:
begin to set demoGC to null
demoGC was set null
begin to run gc
gc was runed 
Demo finalized
结论:
 所以finalize方法只有在JVM执行gc时才会被执行,所以我们在写代码用到的时候需注意。
*/


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值