Java并手动执行finalize [英] Java and manually executing finalize

查看:125
本文介绍了Java并手动执行finalize的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从程序代码中调用 finalize()对象, JVM 仍会在垃圾收集器进程中再次运行该方法这个对象?

这是一个近似的例子:

  MyObject m = new MyObject(); 

m.finalize();

m = null;

System.gc()

显式调用 finalize()使 JVM 的垃圾收集器不要在对象上运行 finalize()方法 m

解决方案

根据这个简单的测试程序,仍然会调用finalize(),即使你明确地调用它:

  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);
}

输出结果为:


开始

完成!

完成!

完成


每个资源都表示永远不会显式调用finalize(),并且几乎从不实现该方法,因为不能保证它是否以及何时会被调用。您最好手动关闭所有资源。


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?

This would be an approximate example:

MyObject m = new MyObject();

m.finalize();

m = null;

System.gc()

Would the explicit call to finalize() make the JVM's garbage collector not to run the finalize() method on object m?

解决方案

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");
}

The output is:

start
finalizing!
finalizing!
done

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆