ExecutorService 中的 InterruptedException

InterruptedException inside ExecutorService

ExecutorService 管理的任务中捕获 InterruptedException 时,我们是否应该设置中断标志?或者我们应该吞下 InterruptedException?

示例:

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

service.submit(() -> {
    try {
        while (!condition) {
            object.wait();
        }
    } catch (final InterruptedException exception) {
        Thread.currentThread().interrupt(); // yes or no?
    }
});

正如这个 article 所建议的那样,永远不要吞下 InterruptedException。

在提交给ExecutorService的任务中,接收到中断是取消任务执行的信号。所以,在你的代码示例中,答案是"no",不要再设置中断。

据我在源代码中所见,重新断言中断状态将被忽略,但它确实浪费了执行程序中的一些工作,因为如果 InterruptedException 立即引发工作线程尝试获取另一个任务,然后根据执行程序的状态确定该任务是虚假的并被清除。

及时关闭执行器取决于响应中断而退出的任务;它不依赖于恢复中断状态的任务。