Is there a destructor for Java?

前端 未结 22 1714
[愿得一人]
[愿得一人] 2020-11-22 11:47

Is there a destructor for Java? I don\'t seem to be able to find any documentation on this. If there isn\'t, how can I achieve the same effect?

To make my question m

22条回答
  •  佛祖请我去吃肉
    2020-11-22 12:26

    Many great answers here, but there is some additional information about why you should avoid using finalize().

    If the JVM exits due to System.exit() or Runtime.getRuntime().exit(), finalizers will not be run by default. From Javadoc for Runtime.exit():

    The virtual machine's shutdown sequence consists of two phases. In the first phase all registered shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish. In the second phase all uninvoked finalizers are run if finalization-on-exit has been enabled. Once this is done the virtual machine halts.

    You can call System.runFinalization() but it only makes "a best effort to complete all outstanding finalizations" – not a guarantee.

    There is a System.runFinalizersOnExit() method, but don't use it – it's unsafe, deprecated long ago.

提交回复
热议问题