If I add a shutdown hook to my Java program's runtime like so:
public class MyShutdownHook implements Runnable
{
@Override
public void run()
{
// Stuff I want executed anytime
// the program, Java, or the OS exits normally,
// crashes, or terminates unexpectedly for any reason.
}
}
// The in another method...
Runtime.getRuntime().addShutdownHook(new MyShutdownHook());
...then are there ever any situations where that run()
method won't execute when the program/Java/OS exits normally, crashes or terminates unexpectedly? If so, what situations would be able to by-pass Runtime
's shutdown hook, and why?
If the process is killed, a shutdown hook will not be executed.
If the process crashes, a shutdown hook will not be executed.
If you have a Windows service and the shutdown hook takes to long to execute, it will be terminated.
If you pull the plug out the back of your computer then the shut-down hook won't run. Other situations include:
- The process being killed on a POSIX OS with SIGKILL (-9).
- Similarly if you elect to terminate an "unresponsive" process under Windows the shut-down hook may not complete.
They only run if the process "shuts down normally." If the process is killed forcefully from the OS or if it's crashing due to resource issues (e.g., out of memory), shutdown hooks won't be invoked.
when you do Runtime.getRuntime().halt()
the JVM or when the OS kills the process without allowing it to run any cleanup, also when you have eclipse terminate the program (when running it under eclipse)
Any time the JVM can exit gracefully, the shutdown hook is run. It is not run if:
- The JVM crashes. (Depending on how/when it crashes, the hook may still run, but no guarantees are made)
- The JVM gets SIGKILL or similar, and is immediately stopped by the OS
来源:https://stackoverflow.com/questions/8171646/when-shutdown-hooks-break-bad