6

I am very confused and not able to understand why InterruptedException should not be swallowed.

The article from IBM says

When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;

    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }

    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
           Thread.currentThread().interrupt();//preserve the message
             return;//Stop doing whatever I am doing and terminate

         }
    }
}

Also,Java Concurrency in Practice discusses this in more detail in Chapter 7.1.3: Responding to Interruption. Its rule is:

Only code that implements a thread's interruption policy may swallow an interruption request. General-purpose task and library code should never swallow interruption requests.

1.Can anyone explain how can code in higher call stack make use of the status set by Thread.currentThread().interrupt(); in catch block when the thread is terminated?

Also Please explain the above rule?

4

1 回答 1

6

看一下这个例子,我们假设在线程/线程池上下文中运行。

public void run() {
  // Honor interrupts so that you can stop/kill the task
  while (!Thread.currentThread().interrupted()) {
    this.doSomeChunkOfWork();
  }    
}

上面的代码是一个很好的例子,说明了如何编写一个可以被中断的任务并以块的形式处理数据(想想从一些源中读取数据并部分地处理数据)。现在让我们假设doSomeChunkOfWork被中断并且你捕获了一个异常。除非你再次设置标志或者保持标志的中断状态,否则run当方法调用返回时,方法将无法知道调用堆栈深处的处理被中断,这会破坏我们良好的逻辑。

这就是为什么您总是将状态设置回来以便调用堆栈中的方法知道线程是否真的被中断的原因。我想对此进行类比是“不要在地毯下扫尘”。:)

于 2013-09-08T09:47:32.687 回答