ExecutorService内部的InterruptedException [英] InterruptedException inside ExecutorService

查看:105
本文介绍了ExecutorService内部的InterruptedException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在由 ExecutorService 管理的任务中捕获 InterruptedException 时,我们应该设置中断标志吗?还是我们应该吞下 InterruptedException ?

Should we set the interrupted flag when catching an InterruptedException inside a task managed by an ExecutorService? Or should we just swallow the InterruptedException?

示例:

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

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

推荐答案

在提交给 ExecutorService 的任务中,接收到中断是取消任务执行的信号.因此,在您的代码示例中,答案是否",请不要再次设置中断.

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.

据我在源代码中看到的,重新声明中断状态将被忽略,但是由于如果立即引发 InterruptedException ,则会在执行程序中浪费一些工作.工作线程尝试获取另一个任务,然后根据执行程序的状态将其确定为虚假并清除.

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.

这篇关于ExecutorService内部的InterruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆