Why should we not swallow the InterruptedException
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) {
// Restore the interrupted status
Thread.currentThread().interrupt();
}
}
}
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.
Can anyone explain how can code in higher call stack make use of the
status set by Thread.currentThread().interrupt(); in catch block?
Also Please explain the above rule.
No comments:
Post a Comment