Why we should not swallow InterruptedException

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

An IBM article says:

When the lock method detects an interrupt and throws an InterruptedException, it clears the interrupted status. If you catch an InterruptedException but cannot recover it, you must save evidence that an interrupt has occurred so that the code above in the call stack can learn about the interrupt 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 } } } 

In addition, Java Concurrency in practice discusses this in more detail in Chapter 7.1.3: โ€œInterrupt Responseโ€. His rule:

Only code that implements a thread interrupt policy can swallow an interrupt request. The target code and general purpose libraries should never swallow interrupt requests.

1. Can someone explain how code in a higher call stack uses the status set by Thread.currentThread (). interrupt (); in the catch block when the thread terminates?

Also explain the rule above?

+4
source share
1 answer

Take a look at this example, which allows assuming execution in the context of a stream / stream.

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

The above code is a good example of how you should write a task that can be interrupted and process the data in pieces (think about reading from some source and processing the data in parts). Now suppose that doSomeChunkOfWork is aborted and you get an exception. If you do not set the flag again or do not save the flag's interrupt status, the run method will not be able to know that processing in the back of the call stack was interrupted when the method call returned, which ruined our good logic.

This is the reason you always return status so that methods in the call stack know whether the thread was actually interrupted or not. The analogy Iโ€™d like to think about is โ€œdon't sweep the dirt under the rug.โ€ :)

+4
source

Source: https://habr.com/ru/post/1501149/


All Articles