问题
I have question regarding the finalize method. If I have many classes with many inheritances, how can I call all finalize methods when the application closing?
回答1:
System.runFinalizersOnExit(true)
, but note that it's deprecated. If you're relying on this sort of thing you're already doing something wrong basically.
回答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.
回答3:
If your need is to clean up things, to close a log file, to send some alert, or take some other action when the Java Virtual Machine is shutting down especially if someone presses CTRL+C and shutdown the VM, or sends a kill signal in Unix/Linux, then you must look at ShutdownHook.
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt. Note that daemon threads will continue to run during the shutdown sequence, as will non-daemon threads if shutdown was initiated by invoking the exit method.
回答4:
It's not best to rely on finalize() to do cleanup of resources in JVM.
From Javadoc.
Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
Edit : Refer this blog about finalize() usage
来源:https://stackoverflow.com/questions/18681412/java-finalize-method-call-when-close-the-application