您的位置:首页 > 其它

finalize()方法调用的时机

2015-09-09 09:41 627 查看
【示例一】

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时才会被执行,所以我们在写代码用到的时候需注意。
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: