Created
November 16, 2017 18:41
-
-
Save jklingsporn/b39128fac9c6d8cfe2a3e71241815c12 to your computer and use it in GitHub Desktop.
Converts List<CompletableFuture<X>> to a CompletableFuture<List<X>>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static<T> CompletableFuture<List<T>> sequence(List<CompletableFuture<T>> com) { | |
return CompletableFuture.allOf(com.toArray(new CompletableFuture[com.size()])) | |
.thenApply(v -> com.stream() | |
.map(CompletableFuture::join) | |
.collect(toList()) | |
); | |
} |
Just a clarification for diversit :
join will never block here, "CompletableFuture.allOf" waits for all futures to be done before calling the lambda passed to thenApply. If "join" throws an exception, the returned completableFuture will complete exceptionally, as with all methods returning completableFutures, the caller will have to decide how to handle the exceptional behavior.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is not true non-blocking since
join
blocks and also might throw an exception which is not handled.Have a look at this implementation: https://gist.github.com/diversit/add7524def84fe20f9cfd73db5728ff2