Reputation: 1558
I have to call three methods from a method. These three methods in turn call various REST or SOAP services. I want to make processing of these three methods to be asynchronous i.e. the rest calls and soap calls are made in parallel. Also, I want main thread to wait for all these threads to complete and then do some processing on the data received by the threads. What is the best way to achieve this? I guess I could look into following ways -
Are there any other ways? Which of the above ways is the best for my scenario?
Upvotes: 1
Views: 1085
Reputation: 1767
executor service + Completable futures
List<CompletableFuture<SomeResponse>> futures = new ArrayList<>();
//assign futures to executor
futures.add(CompletableFuture.supplyAsync(() -> client.perform(request), executor));
...
//create combined future
CompletableFuture combinedFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
//wait for all features to execute or timeout
combinedFuture.get(50, TimeUnit.SECONDS);
//go through results
for (CompletableFuture<SomeResponse> future : futures){
...
}
Upvotes: 2