I am using a ThreadPool via ExecutorService. By calling shutDownNow() it interrupts all running threads in the pool. When this happens I want these threads to give up their resources (socket and db connections) and simply die, but without continuing to run anymore logic, eg: inserting anything into the DB. What is the simplest way to achieve this? Bellow is some sample code:
edit: forgot to mention that all my connections are released via finally. I just need to make sure that reaching that doesn’t invoke various DB inserts in a reliable way.
public void threadTest() {
Thread t = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(999999);
} catch (InterruptedException e) {
//invoke thread suicide logic here
}
}
});
t.start();
t.interrupt();
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
}
The canonical way to do this, in my opinion, involves never catching the InterruptedException at all.
You should always be releasing your resources in a
finallyblock anyway, regardless of this issue – so let’s assume that you are. In this case, all you need to do is let the InterruptedException bubble up to the top level (i.e. declare it in thethrowsclause for all of your methods) and voila!Some may baulk at adding a checked exception to all of the methods. However, this is conceptually correct – a method declared to throw
InterruptedExceptionis signifying that it is a blocking method. Ordinarily, only low-level methods would implement this, as higher-level methods are seldom definitively going to involve blocking (i.e. one could come up with a plausible alternative implementation/defer to an alternative dependency that did not require it).The really questionable thing is that you want your code to “just stop” like this. You don’t really have the context to do such a thing unconditionally from a thread manager, the code running in the threads needs to co-operate with your efforts. So letting the interrupted exception bubble is one approach; another could be to catch this exception relatively low down and set a boolean
stopflag which you poll in the higher-level code.In any case, the question here is solely around how to get higher-level code to know that it should terminate in this case. If you’re closing resources in
finallyblocks, as you should, then you know that they will always be released appropriately regardless of anything else.