views:

218

answers:

2

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.

A: 

It sounds like you need a multi-step shutdown process. In a multithreaded environment, I wouldn't count on simply evaluating the lines of codes you need to execute in order to give you guidance on your shutdown procedure...

jldupont
There is one in place but it all messes up if the user click on the X.
Android
Android, you can intercept a click to closing the window by setting the default behaviour on close to DO_NOTHING and then adding a WindowListener (e.g. WindowAdapter) to perform the relevant shut-down functions prior to calling System.exit. Might be an easier route then using a shut-down hook.
Adamski
+3  A: 

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.

Adamski
Thanks. I will try it then.
Android
You should also have the shutdown thread wait for the queue thread to finish. Otherwise you could end up in the situation where the all the shutdown threads terminate and the process is shutdown before the queue finishes.
Tom Hawtin - tackline
@Tom: Yeah that's a really good point.
Adamski
Thanks Tom, didn't think about that. May need to redesign a little to implement that but it should be done.
Android