CompletableFuture 如何先 return FALSE 或等到所有完成后才 return TRUE

CompletableFuture how to return first FALSE or wait until all are completed to return TRUE

我有一点奇怪的情况,似乎不允许这个挂钩适合任何广泛建立的 CompletableFuture 孔。

现在,我正在使用基本的 && 链来进行此评估:

public boolean evaluateChecks() {
    return checkOne().Join() && checkTwo().Join() && checkThree().Join();
}

然而,这仍然按照特定顺序执行操作 - 如果 checkThree() 是第一个 return FALSE 值,它仍然必须等到前两个提供了它们的值才能获得评估,由于 && fall-through 的工作原理。

目前所有三种方法 return CompletableFuture<Boolean>,但我可以毫无问题地将它们还原为正常方法以便 运行 成为主要方法中的 CompletableFuture评估它们。

我看过 quite a few examples,但 none 似乎提供了我需要的功能。

改编自 Didier L 的回答:

不使用 exceptionallycompleteExceptionally,而是使用 thenAcceptcompleteallOf() 编辑的 CompletableFuture return .

例如,保存期货因为您要对它们进行连锁操作:

CompletableFuture<Boolean> a = checkOne(), b = checkTwo(), c = checkThree();

使用CompletableFuture.allOf等待它们全部完成(大概你不期望failures/exceptions)并将Void结果转换为预期的Booleantrue.

CompletableFuture<Boolean> allWithFailFast = CompletableFuture.allOf(a, b, c).thenApply(__ -> a.join() && b.join() && c.join());
// if there is an exception, it'll be propagated to the future returned by thenApply

使用上面的 returned CompletableFuture,如果任何原始期货以 false 完成,您现在可以 complete 它更快。

Stream.of(a, b, c).forEach(f -> f.thenAccept(result -> {
    if (!result) {
        allWithFailFast.complete(false);
    }
}));

根据完成的顺序及其结果,allOf 未来将首先完成并评估未来,或者其中一个未来将 return false 和导致 allWithFailFastfalse.

完成

如果多个 futures 以 false 完成,仅第一个调用

allWithFailFast.complete(false);

会做任何事情,其他的基本上会被忽略。