问题
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?
}
});
回答1:
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.
回答2:
As this good article suggest, don't ever swallow InterruptedException.
来源:https://stackoverflow.com/questions/36364224/interruptedexception-inside-executorservice