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?
-
3It is far better to design your system so you don't need this as there is not a reliable way currently. – Peter Lawrey Sep 08 '13 at 07:35
4 Answers
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.

- 305,947
- 44
- 307
- 483
-
4
-
1+1 It is unsafe in the sense you cannot guarantee they will be run (most likely they will) – Peter Lawrey Sep 08 '13 at 07:34
-
2@PeterLawrey No. If you call this it *is* guaranteed. That's what it's for. It is unsafe for the reasons given in the Javadoc. – user207421 Sep 08 '13 at 07:49
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.

- 305,947
- 44
- 307
- 483

- 11,622
- 7
- 51
- 61
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.

- 8,409
- 8
- 48
- 73
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

- 3,706
- 1
- 25
- 38