Search code examples
javaruntimeshutdown

When Shutdown Hooks Break Bad


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?


Solution

    • 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.