How java thead pool works with interrupted thread

I am creating a ThreadPool with 10 fixed threads in it. Sometimes I have to interrupt a long thread in the thread pool, mainly because they are blocked in some operation and a timeout occurs, and I interrupt the thread. I catch InterruptedException and set Thread status as well. In this case, my question is: ThreadPool create a new thread and replace the interrupted thread with a new one? The following is an example of the code that Thread runs. The question is, when a thread is interrupted, does the 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) { Thread.currentThread().interrupt(); } catch (ExecutionException ex) { //create a blank response } return response; } 
+8
java threadpool
source share
2 answers

You should not interrupt flows that you do not “own” because you do not know how they react. Since you do not control thread scheduling, you really do not know that a given thread is performing a specific task at the moment you interrupt it.

If you want to cancel the job that you provided to the executor service, call cancel(true) in the corresponding Future . When your task detects an interrupt request, it should maintain an interrupted status by calling Thread.currentThread().interrupt() .

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

+7
source share

From step by step debugging, I assume that the interrupted thread will continue to getTask from the work queue. The interrupted status is already cleared to getTask.

For example, if you use FixedThreadPool with a LinkedBlockingQueue, the interrupted status is cleared inside queue.take() on ReentrantLock.lockInterruptibly()

 public final void acquireInterruptibly(int arg) throws InterruptedException { if (**Thread.interrupted()**) throw new InterruptedException(); if (!tryAcquire(arg)) doAcquireInterruptibly(arg); } 
0
source share

All Articles