Java and manually executing finalize(Java和手动执行finalize)
问题描述
如果我从我的程序代码中对一个对象调用 finalize(),当垃圾收集器处理这个对象时,JVM 是否仍会再次运行该方法?
If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object?
这是一个大概的例子:
MyObject m = new MyObject();
m.finalize();
m = null;
System.gc()
显式调用 finalize() 是否会使 JVM 的垃圾收集器不在对象上运行 finalize() 方法代码>m?
Would the explicit call to finalize() make the JVM's garbage collector not to run the finalize() method on object m?
推荐答案
根据这个简单的测试程序,即使你显式调用了它,JVM 仍然会调用 finalize():
According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it:
private static class Blah
{
public void finalize() { System.out.println("finalizing!"); }
}
private static void f() throws Throwable
{
Blah blah = new Blah();
blah.finalize();
}
public static void main(String[] args) throws Throwable
{
System.out.println("start");
f();
System.gc();
System.out.println("done");
}
输出是:
开始
完成!
完成!
完成
start
finalizing!
finalizing!
done
那里的每个资源都说永远不会显式调用 finalize(),甚至几乎永远不会实现该方法,因为无法保证是否以及何时调用它.最好手动关闭所有资源.
Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually.
这篇关于Java和手动执行finalize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java和手动执行finalize
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
