There is no guarantee that a finalizer will ever run. finalize()
is called when the object is garbage collected. But the garbage collector may not collect anything when the program runs.
Shutdown hooks by contrast are run when the jvm exits normally. so even that isn't 100% guarantee either but it's pretty close. There are only a few edge cases where a shutdown hook doesn't run.
EDIT
I looked up the edge cases where a shutdown hook is not executed
Shutdown hook IS executed:
- When all of JVM threads have completed execution
- Because of call to System.exit()
- Because user hit CNTRL-C
- System level shutdown or User Log-Off
Shutdown hook IS NOT executed:
- If the VM crashes due to an error in native code then no guarantee can be made about whether or not the hooks will be run.
- If JVM is killed using -kill command on Linux or Terminate Process on windows, then JVM exits instantly
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…