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


基础教程推荐
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01