Search code examples
javamultithreadingapplication-shutdown

Can a shutdown hook rely on another thread?


In a shutdown hook method, I need it to send a message to another process to say it has shutdown. My current message handling code requires that the message be written into a queue, this queue is processed by another thread and sent on to wherever it is going. In this case, to be written into a pipe file by another thread.

In a shutdown hook, can I guarantee that these threads will still be running? I have several shutdown hooks but these are all to handle other things that don't need other threads.

The execution is minimal. It will run about 15 lines of code + any wait needed to write into the file which should also be minimal.


Solution

  • From the Javadoc description of addShutdownHook:

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

    Given this I would say that it is safe to assume that your thread will still be running and that you're able to communicate with it. Only thing I would warn against is relying on your shut-down hooks running in a deterministic order.