InterruptedException inside ExecutorService

余生颓废 提交于 2020-08-27 21:28:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!