InterruptedException inside ExecutorService
Asked Answered
L

2

8

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?
    }
});
Leukoderma answered 1/4, 2016 at 19:17 Comment(2)
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.Drucilla
Inside a ExecutorService, what is the difference between swalling and not swalling the exception? How does the ExecutorService behaves in both cases?Leukoderma
H
6

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.

Hasheem answered 1/4, 2016 at 20:59 Comment(3)
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)?Leukoderma
@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.Hasheem
Clear answer! Thank you!Leukoderma
G
0

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

Gilbertine answered 1/4, 2016 at 20:22 Comment(1)
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.Leukoderma

© 2022 - 2024 — McMap. All rights reserved.