Java – shutdown hook and finalizer methods
I just don't understand why I have to use runtime addShutdownHook. If you want to do some cleanup when the JVM exits, why not just overload the finalize method of the daemon class What are the advantages of using Shutdown hook over the finalize method?
There is also a deprecated function, runfinalizesonexit If I set it to false, I believe the finalizer will not run This is similar to Java, which ensures that the terminator always runs before garbage collection
Solution
There is no guarantee that the terminator will never run When the object is garbage collected, call finalize() But when the program is running, the garbage collector may not collect anything
When the JVM exits normally, the runtime closes the hook So even if this is not a 100% guarantee, it is quite close Only a few edge cases close the hook and do not run
Edit I looked for an edge condition where the shutdown hook was not executed
Execute shutdown hook:
>When all JVM threads have finished executing > because system Exit() because the user calls cntrl-c > system level shutdown or logs off
Shutdown hook does not execute:
>If the VM crashes due to an error in the local code, there is no guarantee that the suspend will run. > If you use the - Kill Command on Linux or the terminate process on windows to terminate the JVM, the JVM exits immediately