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

问题描述 投票:1回答:1

具有以下暂存代码:

  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()中并行执行过程中引发的所有异常并将其映射到List。

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

具有以下暂存代码:公共静态void main(String [] args)抛出ExecutionException,InterruptedException {CompletableFuture process1 = CompletableFuture.runAsync(()-&...

java asynchronous completable-future java-threads
1个回答
2
投票

[如果您想避免返回CompletableFuture<Exception>并且仅能够首先抛出并且比仍然能​​够执行某些操作,则会从所有CompletableFuture中收集异常。

© www.soinside.com 2019 - 2024. All rights reserved.