Skip to content

Instantly share code, notes, and snippets.

@javareboots
javareboots / FirstResponseMultipleParallelRequests.java
Last active February 24, 2021 10:56
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));