I am investigating the use of Java 8 CompletableFuture
.
The process I am attempting to code is as follows:-
Extract Keys
1). Execute a single CompletableFuture
that returns a List<String>
Extract Data
2). On completion of step 1). Execute multiple CompletableFutures
in parallel that accept this List<String>s
as input. Each CompletableFuture
executed in step 2). returns a unique list of Value Objects.
Combine Data
3). Once all CompletableFutures
executed in step 2). have completed I wish to combine the individual lists of Value Objects and complete the process.
The code I have working can only cope with two CompletableFutures executing during Step 2). as follows:-
final CompletableFuture<List<String>> extractor = get("https://example.com//source/url");
final CompletableFuture<List<Documentable>> valueObjectList1 = extractor.thenApplyAsync(s -> callTypeADocumentable(s));
final CompletableFuture<List<Documentable>> valueObjectList2 = extractor.thenApplyAsync(s -> callTypeBCDocumentable(s));
valueObjectList1.thenCombineAsync(valueObjectList2, (c, e) -> consumeBothDocumentable(c, e)).thenAccept(x -> finish(x));
My desired solution is to achieve this:-
final CompletableFuture<List<String>> extractor = get("https://example.com//source/url");
@SuppressWarnings("unchecked")
final CompletableFuture<List<Documentable>>[] completableFutures = new CompletableFuture[ENDPOINT.values().length];
int index = 0;
for (ENDPOINT endpoint : ENDPOINT.values()) {
final CompletableFuture<List<Documentable>> valueObjectList = extractor.thenApplyAsync(s -> endpoint.contactEndpoit(s));
completableFutures[index++] = valueObjectList;
}
completableFutures[0].allOf(completableFutures[1], completableFutures[2], ...);
How can I combine multiple CompletableFutures
(e.g. More than two) in the same manner as I did for exactly two CompletableFutures