如果我从我的程序代码中对一个对象调用 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!