1

我知道当垃圾收集器确定不再有对该对象的引用时,垃圾收集器会在对象上调用 Java finalize 方法。

Java finalize() 方法会在应用程序退出后执行吗?

4

3 回答 3

5

Will a Java finalize() method execute after an application exits?

Normally no.

However, there is a (deprecated!) method that you can call to tell the JVM to finalize objects on JVM exit. The problem is that it can cause bad things to happen; e.g. erratic behaviour and deadlocks. So don't use it!


In general, it is a bad idea to use finalize in application code. If what you are trying to do here is to implement some shutdown-time behaviour, then a better approach is to implement the behaviour as a shutdown hook.

于 2013-09-21T03:03:22.520 回答
3

No. You can call Runtime.runFinalizersOnExit(), but it's deprecated so it may not function.

A workaround would be to create a shutdown hook with Runtime.addShutdownHook() and do all your cleanup in the hook.

于 2013-09-21T03:03:11.163 回答
2
finalize() methods do not run on application exit.

The recommended approach is to use a shutdown hook.

e.g.

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
        // shutdown logic
    }
});

The shutdown hook is executed when: - the program exits normally e.g. System.exit - a user interrupt e.g. typing ^C, logoff, or system shutdown

Java also offers a method called, runFinalizersOnExit() which was @deprecated. It was deprecated for the following reason:

It may result in finalizers being called on live objects 
while other threads are concurrently manipulating those objects, 
resulting in erratic behavior or deadlock

Essentially, runFinalizersOnExit() is unsafe. Use a shutdown hook as I've described above.

于 2013-09-21T03:04:25.817 回答