views:

280

answers:

3

In Effective Java (page 275), there is this code segment:

...
for (int i = 0; i < concurrency; i++) {
  executor.execute(new Runnable() {
    public void run() {
    ready.countDown();
    try {
      start.await();
      action.run();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } finally {
      done.countDown();
    }
  }
}
...

What's the use of catching the interrupted exception just to re-raise it? Why not just let it fly?

+5  A: 

The simple answer is that InterruptedException is a checked exception and it is not in the signature of the Runnable.run method (or the Executable.execute() method). So you have to catch it. And once you've caught it, calling Thread.interrupt() to set the interrupted flag is the recommended thing to do ... unless you really intend to squash the interrupt.

Stephen C
Assuming you want the thread to be actually interrupted. You can just catch and swallow the exception as well which will suppress the thread interruption.
Francis Upton
You mean it's not in the signature of Runnable. I'd use a Callable instead. Also - calling Thread.currentThread().interrupt() will not throw that exception? So what's the point in throwing it?
ripper234
I believe you mean that the `InterruptedException` is a checked exception and is not in the signature of `Runnable.run()` (not `Executor.execute`).
Tom
@Francis, @Tom, @ripper yes ... corrected
Stephen C
A: 

Sometimes you can't ignore exception and you must catch it. Mainly this happens when you override method which can't throw InterruptedException in accordance with its signature. For example, this approach is usually used in Runnable.run() method.

alygin
A: 

The executor can interrupt tasks if they are cancelled but it clears the interrupted flag between tasks to avoid one cancelled task interrupting an unrelated task.

As such, interrupting the current thread here would be dangerous if it actually did anything.

A simpler way around this is to use Callable or ignore the interrupt.

Additionally it is a good idea to catch and log any error or exception thrown in the try/catch block otherwise the exception/error will be discarded and your program could be failing but you won't know it is or why.

Peter Lawrey