user4460845
user4460845

Reputation:

InterruptedException inside ExecutorService

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?
    }
});

Upvotes: 8

Views: 6420

Answers (2)

erickson
erickson

Reputation: 269627

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.

Upvotes: 6

Matteo Baldi
Matteo Baldi

Reputation: 5828

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

Upvotes: 0

Related Questions