我知道当垃圾收集器确定不再有对该对象的引用时,垃圾收集器会在对象上调用 Java finalize 方法。
Java finalize() 方法会在应用程序退出后执行吗?
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.
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.
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.