However, there are quite a few threads spread through different areas of the code. If I had to manually close every one of the threads when a shutdown is called, well it could be a bit of a pain to get logic flow perfect without missing some obscure daemon.
Unfortunately the best way to do this is as you imply. You should have a destroy()
method on the classes that fork threads so they can explicitly clean up after themselves. But this does require someone calling those destroy methods when the application is terminating.
What I would like to do instead is to have a thread that is like a daemon thread, but has a certain critical section where it cannot be killed until it completes (or maybe times out if it takes too long?).
There is nothing in the Java threads that allows this behavior. Either a thread is daemon or it is not and this is set before the thread starts.
Is there an easy way to get this behavior just by instantiating a class or setting a Boolean
I think you are on to something here. I would have a ThreadUtils
class with a volatile boolean shutdown
field.
public class ThreadUtils {
private static volatile boolean shutdown = false;
/** called by main when the application is shutting down */
public static void shutdown() {
shutdown = true;
}
/** used by the various non-daemon threads to test for shutdown */
public static boolean isShutdown() {
return shutdown;
}
}
You main program would set the shutdown flag to true and then all of your threads would need to check this boolean in their code:
// we can test for shutdown only at "appropriate" points in the thread
while (!ThreadUtils.isShutdown()) {
...
// we are not ready to be killed here
...
}
Something like this pattern, although a bit gross, sounds like it fulfills your requirement.