7

Should we set the interrupted flag when catching an InterruptedException inside a task managed by an ExecutorService? Or should we just swallow the InterruptedException?

Example:

final ExecutorService service = ...;
final Object          object  = ...;

service.submit(() -> {
    try {
        while (!condition) {
            object.wait();
        }
    } catch (final InterruptedException exception) {
        Thread.currentThread().interrupt(); // yes or no?
    }
});
  • 5
    It depends on the context and the requirements. Rule of thumb, don’t swallow unless you know what you are doing and have good reasons. – Ole V.V. Apr 01 '16 at 19:56
  • 2
    Inside a `ExecutorService`, what is the difference between swalling and not swalling the exception? How does the `ExecutorService` behaves in both cases? –  Apr 01 '16 at 20:31

2 Answers2

4

In a task submitted to an ExecutorService, receiving an interrupt is a signal to cancel execution of the task. So, in your code example, the answer is "no", don't set the interrupt again.

Re-asserting the interrupt status, as far as I can see in the source code, will be ignored, but it does waste a bit of work in the executor as an InterruptedException is raised immediately if the worker thread tries to get another task, which is then determined to be spurious and cleared based on the state of the executor.

Shutting down the executor in a timely manner depends on tasks exiting in response to an interrupt; it does not depend on tasks restoring the interrupt status.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • Note that the `InterruptedException` not only happens when the executor is asked to `.shutdown()`. This also happens if the corresponding `Future>` is asked to `.cancel(true)`. Will the `ExecutorService` also behave the same in both cases (swallowing or not)? –  Apr 01 '16 at 21:06
  • @JasarTolio Yes, it behaves the same. I was speaking primarily about `Future.cancel()` calls in my answer; abrupt shutdown can be thought of as requesting a `cancel()` on any submitted tasks. The only effect of an interrupt on a worker thread of `ThreadPoolExecutor` is to make it wake up and check the state of the executor. If that state hasn't actually changed, it will go back to `poll()` or `take()` the next task from the work queue. – erickson Apr 01 '16 at 21:39
  • Clear answer! Thank you! –  Apr 02 '16 at 05:55
0

As this good article suggest, don't ever swallow InterruptedException.

Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
  • 2
    The article is quite old, and does not take the modern Java Concurrent package into account. The ideas are ofcourse the same, but the context might be different since the `ExecutorService` is in charge. –  Apr 01 '16 at 21:16