gpt4 book ai didi

java - 为什么java中的finalize()方法不在Finalizer类中?为什么它被定义在对象类中?

转载 作者:行者123 更新时间:2023-12-04 10:57:35 24 4
gpt4 key购买 nike

为什么java中的finalize()方法不在Finalizer类中?为什么定义在Object Class中?

最佳答案

  1. “终结器”类,java.lang.ref.Finalizer和“finalizer()”方法,java.object.finalize是两个独立的、截然不同的事物。

  2. 正如 alexey 提到的“finalize()”,

You can override [finalize()] ... to specify what to do when a given object is collected by garbage collector.

  1. 此处讨论了“Finalizer 类”的用途、角色和生命周期:

http://www.fasterj.com/articles/finalizer2.shtml

The JVM will ignore a trivial finalize() method ... Otherwise, if an instance is being created, and that instance has a non-trivial finalize() method defined or inherited, then the JVM will do the following:

  • The JVM will create the instance

  • The JVM will also create an instance of the java.lang.ref.Finalizer class, pointing to that object instance just created (and pointing to a queue that it will be put on by the GC)

  • The java.lang.ref.Finalizer class holds on to the java.lang.ref.Finalizer instance that was just created (so that it is kept alive, otherwise nothing would keep it alive and it would be
    GCed at the next GC).

  1. 所以回答你的问题:“finalize()”是做的事情(在 GC 期间自定义你的对象的清理行为); “Finalize”是 JVM 创建的对象(以促进和管理清理)。

  2. 有很多原因,包括performancesecurity ,除非绝对必要,否则创建自己的自定义终结器通常是的主意。

关于java - 为什么java中的finalize()方法不在Finalizer类中?为什么它被定义在对象类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31774434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com