Skip to content

Instantly share code, notes, and snippets.

@javareboots
Last active February 24, 2021 10:56
Show Gist options
  • Save javareboots/fb94ab0ff8f889e3c5aa8a8998cedf28 to your computer and use it in GitHub Desktop.
Save javareboots/fb94ab0ff8f889e3c5aa8a8998cedf28 to your computer and use it in GitHub Desktop.
Completable Future Example for Multiple Parallel Requests and returning the first Response from them in Java.
/**
An Example where we are calling 4 different Calls and returning the first response that we receive from any of these calls.
Please note this is not a working example, this is a sample code to give you a high level idea.
*/
//Here we create 4 Sample Futures
CompletableFuture<SearchResponse> aggregatorFuture1 = new CompletableFuture<>().supplyAsync(aggregator1.getSearchResult(request));
CompletableFuture<SearchResponse> aggregatorFuture2 = new CompletableFuture<>().supplyAsync(aggregator2.getSearchResult(request));
CompletableFuture<SearchResponse> aggregatorFuture3 = new CompletableFuture<>().supplyAsync(aggregator3.getSearchResult(request));
CompletableFuture<SearchResponse> aggregatorFuture4 = new CompletableFuture<>().supplyAsync(aggregator4.getSearchResult(request));
//Create the List of Above 4 Futures
List<CompletableFuture<String>> aggregatorFuturesList = Arrays.asList(aggregatorFuture1,aggregatorFuture2, aggregatorFuture3, aggregatorFuture4);
//Creating a new Future and using the anyOf() method which uses the list of futures
// that will Returing the first response from any of the 4 futures above
SearchResponse response = CompletableFuture.anyOf(aggregatorFuturesList)
.thenApply(r -> {
if (r instanceof SearchResponse) {
return (SearchResponse) r; //We need to type cast the response as well.
}
throw new Exception("Response type is not of SearchResponse!");
}).join();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment