During my recent interview, i was asked to design the flow of 5 parallel calls and returning the first response that i will get from any of those 5 different calls. I was aware that for parallel calls i will have to somehow use a Future. But the requirement of getting the first response from any of them and returning it as the answer confused me.
Future has been around since a long time now. Even Completable Future has been present since Java 8.
We need to use the anyOf() method to return the first response from the list of futures.
I am sharing my findings below. If you have a better solution please provide your inputs in the comments sections.
/** | |
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(); |