1

I am interested in situations where you catch InterruptedExceptions but preserve the interrupt status ..like below example

try{
    //Some code
    } catch (InterruptedException ie) {
         // (Re-)Cancel if current thread also interrupted
         pool.shutdownNow();
         // Preserve interrupt status
         Thread.currentThread().interrupt();
    }
user207421
  • 305,947
  • 44
  • 307
  • 483
Pushparaj
  • 1,039
  • 1
  • 6
  • 26

1 Answers1

1

You re-interrupt the thread if you need callers to know that an interruption occurred, but you are unable to change your method signature to declare that the method throws InterruptedException.

For instance, if you are implementing java.lang.Runnable, you can't change the method signature to add a checked exception:

interface Runnable {
  void run();
}

So if you do something which throws an InterruptedException in your Runnable implementation, and you are unable to handle it, you should set the interrupted flag on that thread, to allow calling classes to handle it:

class SleepingRunnable implements Runnable {
  @Override public void run() {
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
}

If you are able to change your method signature, it is better to do so: because InterruptedException is a checked exception, callers are forced to handle it. This makes the fact that your thread might be interrupted much more obvious.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • this is a good general description, however your example is not very good. in the case of the run method, nothing else is going to care that the thread was interrupted (the status will be cleared when the method returns). – jtahlborn Apr 05 '16 at 12:28
  • @jtahlborn you don't know that in general. `Runnable.run()` can be run *anywhere*; what you say is only true if it is run by a thread or a standard executor implementation. – Andy Turner Apr 05 '16 at 12:30
  • technically you are right, but how often do you call run on a Runnable not in a thread or executor? – jtahlborn Apr 05 '16 at 12:32