Senior
How to make parallel calls to multiple services to generate a report?
sobes.tech AI
Answer from AI
For parallel invocation of multiple services in Java, you can use CompletableFuture. This allows you to run asynchronous tasks and then combine their results.
Example:
import java.util.concurrent.*;
import java.util.*;
public class ReportService {
private ExecutorService executor = Executors.newFixedThreadPool(10);
public Report buildReport() throws ExecutionException, InterruptedException {
CompletableFuture<String> service1 = CompletableFuture.supplyAsync(() -> callService1(), executor);
CompletableFuture<String> service2 = CompletableFuture.supplyAsync(() -> callService2(), executor);
CompletableFuture<String> service3 = CompletableFuture.supplyAsync(() -> callService3(), executor);
// Wait for all to complete
CompletableFuture<Void> allDone = CompletableFuture.allOf(service1, service2, service3);
// After completion, gather results
allDone.get();
String result1 = service1.get();
String result2 = service2.get();
String result3 = service3.get();
// Assemble report from results
return assembleReport(result1, result2, result3);
}
private String callService1() {
// call first service
return "data1";
}
private String callService2() {
// call second service
return "data2";
}
private String callService3() {
// call third service
return "data3";
}
private Report assembleReport(String r1, String r2, String r3) {
// report assembly logic
return new Report(r1, r2, r3);
}
static class Report {
String part1, part2, part3;
public Report(String p1, String p2, String p3) {
this.part1 = p1;
this.part2 = p2;
this.part3 = p3;
}
}
}
This approach allows efficient use of threads and does not block the main thread, waiting for each service separately. You can also handle errors and timeouts using CompletableFuture methods.