Search code examples
javaruntimeshutdown-hook

What parts of my application can I access and use during a shutdown hook execution?


I am trying to understand when a shutdown hook executes. Is it before or after any part of my application has been stopped? Since my shutdown hook code will be running in a freshly created thread, can I access other non-shutdown-hook threads from it? Or they might be stopped/killed by the exiting JVM?

Of course I am assuming the the JVM is exiting due to an exception and not due to a unrecoverable crash which would not execute the shutdown hooks anyways.


Solution

  • From the Javadoc documentation of Runtime#addShutdownHook:

    The Java virtual machine shuts down in response to two kinds of events:

    • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

    • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

    From the first event, you shouldn't expect that threads are still alive when the shutdown hook is running (except for daemon threads).

    From the same page:

    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.

    When the program terminates due to an exception, all threads will eventually die, which will then the shutdown hook.