首页 > 解决方案 > 如果返回失败的阶段,为什么 thenCombine 结果不能异常完成?

问题描述

以下代码片段调用thenCombine ,并没有在whenComplete设置异常(它打印No exception):

    CompletableFuture.completedFuture(true)
    .thenCombine(CompletableFuture.completedFuture(true),
        (x,y) -> {
        return CompletableFuture.failedStage(new RuntimeException());
    })
    .whenComplete( (myVal, myEx) -> {
      if (myEx == null) {
         System.out.println("No exception");
      } else {
         System.out.println("There was an exception");
      }
    });

但是,下面调用thenCompose的类似代码确实设置了一个异常:

    CompletableFuture.completedFuture(true)
    .thenCompose(
        x -> {
          return CompletableFuture.failedStage(new RuntimeException());
        })
    .whenComplete( (myVal, myEx) -> {
      if (myEx == null) {
        System.out.println("No exception");
      } else {
        System.out.println("There was an exception");
      }
    });

为什么在 BiFunction 实际上返回失败阶段时thenCombine返回正常完成?CompletionStage

标签: javaasynchronouscompletable-futurecompletion-stage

解决方案


在你的第一个例子CompletableFuture.failedStage(new RuntimeException()) 中是结果。CompletableFuture返回的由thenCombine完成CompletableFuture.failedStage(new RuntimeException())

当您不链接调用时,它会变得更加清晰:

CompletableFuture<Boolean> first = CompletableFuture.completedFuture(true);
CompletableFuture<Boolean> second = CompletableFuture.completedFuture(true);
        
CompletableFuture<CompletionStage<?>> yourQuestion =
        first.thenCombine(second, (x, y) ->
                CompletableFuture.failedStage(new RuntimeException()));

对于您的第二个示例,您需要thenCompose仔细阅读以下文档:

返回一个新的 CompletionStage,它使用与给定函数返回的 CompletionStage 相同的值完成。

在你的函数中thenCompose返回一个失败CompletableFuture它的结果被用作CompletableFuture返回的结果thenCompose:a RuntimeException


推荐阅读