Java和手动执行finalize

Java and manually executing finalize(Java和手动执行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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)