finalize()方法调用的时机
2015-09-09 09:41
627 查看
【示例一】
从示例一的结果来看,并没有在将引用置为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; /** * 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时才会被执行,所以我们在写代码用到的时候需注意。 */
相关文章推荐
- 永远保持可以随时离开的能力
- mybatis foreach 熟悉
- linux调度器(一)——概述
- php排序函数测试
- iOS视图生命周期
- Hibernate – One-to-One example (XML Mapping)
- 三分钟理解Java中字符串(String)的存储和赋值原理
- LeetCode之Basic Calculator II
- mysql基本操作
- UINavigationController 返回上一级,返回根控制器,返回某一级
- TextVIew字体设置
- Python脚本后台运行的几种方式
- 西门子S7-300系列plc和紫金桥软件的通讯
- 六年软件测试感悟 (续一)
- 六年软件测试感悟 (续二)
- 图像美妆算法---自动祛斑算法研究
- hdu 确定比赛名次(拓扑排序)
- 从零单排之玩转Python安全编程(II)
- 查看ORACLE执行计划的几种常用方法
- windows 下一个mysql password忘记改变