Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) { 
           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?

like image 292
beinghuman Avatar asked Sep 08 '13 09:09

beinghuman


1 Answers

Take a look at this example which let's assume runs in a thread/thread-pool context.

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 would write a task which can be interrupted and processes data in chunks (think of reading from some source and processing data in parts). Now let's assume doSomeChunkOfWork is interrupted and you catch an exception. Unless you set the flag again or maintain the interrupt status of the flag, the run method won't be able to know that the processing deep down the call stack was interrupted when the method call returns which messes up our good logic.

This is the reason why you always set the status back so that methods down the call stack are aware of whether the thread was really interrupted or not. An analogy I would like to think for this is "don't sweep dirt under the rug". :)

like image 76
Sanjay T. Sharma Avatar answered Sep 28 '22 22:09

Sanjay T. Sharma