gpt4 book ai didi

java - 从 CompletableFuture.allOf() 执行中收集抛出的异常

转载 作者:行者123 更新时间:2023-12-05 02:09:14 41 4
gpt4 key购买 nike

具有以下暂存代码:

  public static void main(String[] args) throws ExecutionException, InterruptedException {

CompletableFuture<Void> process1 = CompletableFuture.runAsync(() -> {
System.out.println("Process 1 with exception");
throw new RuntimeException("Exception 1");
});

CompletableFuture<Void> process2 = CompletableFuture.runAsync(() -> {
System.out.println("Process 2 without exception");
});

CompletableFuture<Void> process3 = CompletableFuture.runAsync(() -> {
System.out.println("Process 3 with exception");
throw new RuntimeException("Exception 3");
});

CompletableFuture<Void> allOfProcesses = CompletableFuture.allOf(process1, process2, process3);

allOfProcesses.get();
}

我正在寻找如何收集在 CompletableFuture.allOf() 中并行执行期间抛出的所有异常的方法并将其映射到列表。

我知道我可以通过返回异常 ( CompletableFuture<Exception> ) 而不是抛出并使用 CompletableFuture::join 收集它来做到这一点但我认为抛出异常的方法比返回并稍后抛出更好

最佳答案

如果你想避免返回CompletableFuture<Exception>并且能够首先抛出并且仍然能够做一些事情将从所有CompletableFuture中收集异常

在这种情况下,您可以使用 CompletableFuture::exceptionally 收集异常:

private static List<Throwable> collectedExceptions = Collections.synchronizedList(new ArrayList<>());

public static void main(String[] args) throws ExecutionException, InterruptedException {

CompletableFuture<Void> process1 = CompletableFuture.runAsync(() -> {
System.out.println("Process 1 with exception");
throw new RuntimeException("Exception 1");
}).exceptionally(exception -> {
// Handle your exception here
collectedExceptions.add(exception);
return null;
});

CompletableFuture<Void> process2 = CompletableFuture.runAsync(() -> {
System.out.println("Process 2 without exception");
});

CompletableFuture<Void> process3 = CompletableFuture.runAsync(() -> {
System.out.println("Process 3 with exception");
throw new RuntimeException("Exception 3");
}).exceptionally(exception -> {
// Handle your exception here
collectedExceptions.add(exception);
return null;
});

CompletableFuture<Void> allOfProcesses = CompletableFuture.allOf(process1, process2, process3);

allOfProcesses.get();
assert (collectedExceptions.size() == 2);
}

关于java - 从 CompletableFuture.allOf() 执行中收集抛出的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60151502/

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