java - 如何在传播结果或错误时调用 CompletableFuture 回调?

标签 java completable-future

我正在尝试 .exceptionally 和 .handle,但它们似乎不起作用。在 Scala 中,您可以使用类似于 finally block 的闭包调用 future 的方法(它在异常和成功时运行)并且它按原样向上传播异常或成功。

我试过了...

    CompletableFuture<Object> future = newFuture.handle((r, e) -> {
        if(r != null)
            return r;
        else if(e != null)
            return e;
        else
            return new RuntimeException("Asdf");            
    });

    Assert.assertTrue(future.isCompletedExceptionally());

但是由于异常的结果(多么奇怪),该测试失败了,因为 future 完全成功。

最佳答案

使用CompletableFuture#whenComplete(BiConsumer) .它的 javadoc 状态

Returns a new CompletionStage with the same result or exception as this stage, that executes the given action when this stage completes.

When this stage is complete, the given action is invoked with the result (or null if none) and the exception (or null if none) of this stage as arguments. The returned stage is completed when the action returns. If the supplied action itself encounters an exception, then the returned stage exceptionally completes with this exception unless this stage also completed exceptionally.

换句话说,无论成功还是失败,它都会被调用,并且会传播初始 future 的状态(除非 BiConsumer 抛出异常)。

CompletableFuture<String> future2 = newFuture.whenComplete((r, e) -> {
    // consume the result
});

如果您需要转换结果(在您的示例中,您不需要),那么您可以使用 handle 并自己传播内容。

关于java - 如何在传播结果或错误时调用 CompletableFuture 回调?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39187368/

相关文章:

java - Java Maven 项目中 Jenkins 中带点的环境变量

java - OpenJDK 64 位服务器 VM 警告 : Archived non-system classes are disabled (resin, Ubuntu、OpenJDK 11)

java - 使用特定 JRE 版本运行 Applet

java - 我怎样才能跳过异常完成的 future

java - 如果手动完成,则不会调用 CompletableFuture 回调

java - Neo4J 服务器安装 Linux AWS Centos 操作系统 -- 服务用户找不到 java

java - Java 中的边界检查

java - Listenablefuture vs Completablefuture

java - 情境使用 : Run tasks in ForkJoinPool vs. new Thread

java - 扩展 CompletableFuture 时类型不匹配