Shamik Shamik - 1 year ago 71
Java Question

how java thead pool executor deals with interrupted thread

I create a

with 10 fixed threads in it. At times I need to interrupt a longrunning thread in the thread pool, mostly because they are blocking in some operation and a timeout happens and I interrupt the thread. I catch the
and set the Thread's status to interrupt as well. In that case, my question is, does
create a new Thread and replace the interrupted thread with a new One ?
Below is the example code which gets executed by the Thread. Question is, when this thread get interrupted, does thread pool replace this thread with a new one ?

public ResponseMessage call(){
Future<ResponseMessage> future = CacheManager.getInstance().asyncFetch();
ResponseMessage response = null;
try {
response = future.get();
catch (InterruptedException e) {
} catch (ExecutionException ex) {
//create a blank response

return response;

Answer Source

You should not interrupt threads that you do not "own," because you don't know how they respond. Since you don't have control over the thread scheduling, you really don't know that a given thread is executing a particular task at the instant you interrupt it

If you want to cancel a task you've given an executor service, call cancel(true) on its associated Future. When your task detects an interrupt request, it should preserve the interrupted status by calling Thread.currentThread().interrupt().

If you do this, the executor will handle the interruption cleanly because it interrupted the thread itself, and knows that the thread was executing a task when the interrupt occurred.