提问者:小点点

CompletableFuture异常处理runAsync


假设我有这个示例代码,在runAsync中遇到了一个异常。我的问题是,这个异常是否会阻止然后Run作为thenRun在与此代码的调用者方法相同的线程中运行。

private void caller() {
    CompletableFuture.runAsync(() -> {
          try {
              // some code
          } catch (Exception e) {
              throw new CustomException(errorMessage, e);
          }
         }, anInstanceOfTaskExecutor).thenRun(
         // thenRun code
     ));
}

我已经浏览了这个主题,它解释了如何处理从异步块抛出的异常(即通过阻塞和使用连接)。我想知道如果“可完成未来例外地完成那么Run块中的代码是否会被执行。

更新:

我运行了一些代码来测试:

CompletableFuture.runAsync(() -> {
      List<Integer> integerList = new ArrayList<>();
      integerList.get(1);    // throws exception
    }).thenRun(() -> {
      System.out.println("No exception occurred");
    });

它不会打印任何内容,这意味着异常不会从异步块“传播到/到达”调用方方法的线程。我现在了解这里的预期行为,但我有以下问题:

  1. 为什么即使CompletableFuture异常完成,它也会静默失败?
  2. 它在后台是如何工作的?
  3. 是不是因为这两个线程(调用者的线程

共0个答案