CompletableFuture — Aggregate Future to Fail Fast

北城余情 提交于 2019-12-04 09:19:59

Although not as syntactically sweet as the CompletableFuture.allOf(...) method, it appears that thenCompose(...) may offer the solution:

CompletableFuture<?> future = future1.thenCompose((f) -> future2).thenCompose((f) -> future3);

This will yield the desired:

Future1 Complete, aggregate status: false
Future2 Complete, aggregate status: true
Future3 Complete, aggregate status: true

This could be wrapped up in a helper method which would offer some syntactic niceties to the caller:

private static CompletableFuture<?> composed(CompletableFuture<?> ... futures) {

    // Complete when ALL the underlying futures are completed
    CompletableFuture<?> allComplete = CompletableFuture.allOf(futures);

    // Complete when ANY of the underlying futures are exceptional
    CompletableFuture<?> anyException = new CompletableFuture<>();
    for (CompletableFuture<?> completableFuture : futures) {
        completableFuture.exceptionally((t) -> {
            anyException.completeExceptionally(t);
            return null;
        });
    }

    // Complete when either of the above are satisfied
    return CompletableFuture.anyOf(allComplete, anyException);
}

Allowing for:

CompletableFuture<?> future = composed(future1, future2, future3);

You could maybe do this by creating both an allOf and an anyOf, and then combining those into a second anyOf.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!