【问题标题】:InterruptedException thrown from futures从期货抛出的 InterruptedException
【发布时间】:2014-10-09 17:49:22
【问题描述】:

假设我有一个方法如下:

public void poll(Callable<Boolean> callable) {
    ScheduledExecutorService service = Executors.newSingleThreadedScheduledExecutor();

    Future<Boolean> future = service.schedule(callable, 0L, TimeUnit.MILLISECONDS);
    try {
        while (!future.get()) {
            future = service.schedule(callable, 5L, TimeUnit.MINUTES);
        }
    } catch (ExecutionException e) {
        // ...
    } catch (InterruptedException e) {
        // ...
    } finally {
        service.shutdown();
    }
}

InterruptedException 是如何被抛出(并被poll() 捕获)的?可调用对象抛出的任何东西(包括InterruptedException,对吗?)都会是ExecutionException,我们永远不会取消任何期货,并且服务的shutdownNow() 永远不会被调用。

除此之外:既然如此,是否有可能使这种轮询方法对InterruptedException 之类的东西更加防弹?

【问题讨论】:

    标签: java polling scheduledexecutorservice interrupted-exception


    【解决方案1】:

    InterruptedException 将在等待(阻塞)可调用完成时被 get 抛出。

    我不确定你所说的防弹是什么意思,你必须处理抛出异常的可能性。

    【讨论】:

      【解决方案2】:

      InterruptedException 可以由调用 get 并等待完成的线程抛出,而不是由 callable 抛出

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        • 1970-01-01
        相关资源
        最近更新 更多