gpt4 book ai didi

java - CompletableFuture 异常行为与 join() 然后 get()

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:03 25 4
gpt4 key购买 nike

我的直觉是下面的代码是错误的。我相信因为正在使用 join() ,所以在完成 future 时抛出的任何异常都不会被检查。然后在调用get()时,将不会出现已检查的异常,不会记录任何错误,并且在失败时难以诊断错误。

    List<CompletableFuture> list = ImmutableList.of(future1, future2);
CompletableFuture.allOf(list.toArray(new CompletableFuture[list.size()])).join();

try {
result1 = future1.get();
result2 = future2.get();

} catch (InterruptedException | ExecutionException e) {
// will this ever run if join() is already called?
}

我已经查看了 CompletableFuture 的文档,但没有找到我的问题的确切答案。我在这里问,然后将阅读源代码。

我能看到 catch block 代码会运行的唯一原因是,如果检查的异常可以以某种方式保存在某些执行上下文中,而不是在 join() 中抛出(或被未检查的异常包裹抛出),然后再次抛出get() 之后的某种形式。这对我来说似乎不太可能。

所以我的最终问题是,catch block 代码会运行吗?

最佳答案

joinget 方法都是阻塞方法,依赖于完成信号并返回结果T。处理有问题的代码:-

一方面,InterruptedException可能会在线程中断的时候抛出,因为我们做一个get,这里的等待已经被完成了code>join 方法。

此外,如 join 中所述方法文档

/**
* ... if a
* computation involved in the completion of this
* CompletableFuture threw an exception, this method throws an
* (unchecked) {@link CompletionException} with the underlying
* exception as its cause.
*/

因此,另一方面,您的案例中 futureN.get()ExecutionException 只能在未来异常完成时抛出。由于 future 如果异常执行将最终为 join 调用抛出 CompletionException,因此它永远不会到达 catch block ,或者为此 try 阻止其中之一。

关于java - CompletableFuture 异常行为与 join() 然后 get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47015665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com