Skip to content

Instantly share code, notes, and snippets.

@jklingsporn
Created November 16, 2017 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jklingsporn/b39128fac9c6d8cfe2a3e71241815c12 to your computer and use it in GitHub Desktop.
Save jklingsporn/b39128fac9c6d8cfe2a3e71241815c12 to your computer and use it in GitHub Desktop.
Converts List<CompletableFuture<X>> to a CompletableFuture<List<X>>
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())
);
}
@diversit
Copy link

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

@mryan43
Copy link

mryan43 commented Apr 30, 2020

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