在获得超时设置的Future结果时抛出异常的位置?

时间:2016-03-23 21:26:17

标签: java exception concurrency future

如果我运行Future并抛出异常,那么在将Future.get称为ExecutionException时我会遇到这些异常。

但抛出异常的地方,如果我调用Future.get(timeout)并且在超时失效后抛出异常,例如:

    Future<String> future = Executors.newSingleThreadExecutor().submit(() -> {
        Thread.sleep(200);
        System.out.println("COMPLETED");
        throw new Exception("ERROR");
    });
    try {
        future.get(100, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    Thread.sleep(1_000);

有什么想法吗? TIA!

1 个答案:

答案 0 :(得分:1)

在您描述的两种情况下,异常没有什么不同。例如,考虑一下由Future表示的异步任务可能会在您调用其get()方法之前抛出异常而终止。执行程序必须捕获异常并为您保留,直到您调用其中一个get()方法。

当你致电Future.get(long, TimeUnit)并且超时到期时,这并不意味着你永远不会得到结果;它只是意味着你没有通过特定的方法调用得到它。通常,您可以cancel()执行任务,或稍后再试一次以获得结果。