Java Concurrency Program · CD06
Call Services in Parallel with CompletableFuture in Java
Three remote calls of 300 ms each take 900 ms one after another. Started together, they finish in about 300 ms, because the waiting overlaps.
Problem Statement
A product page needs the price, the stock count and the rating, each from a different service that takes about 300 ms to answer.
Fetch all three at the same time and build one summary string. The total time should be close to one call, not the sum of three.
Input/Output Examples
price, then stock, then ratingOutputabout 900 msExplanation: each call waits for the previous one.start all three, then combineOutputabout 300 msExplanation: the calls run at the same time on three threads.499, 12, 4.5Outputprice=499, stock=12, rating=4.5Explanation: the combined values are the same either way.Visual Explanation
- StartthreadspricestockratingsupplyAsync() × 3 no waiting yet
- 300 ms laterdone499124.5all three finish together
- Combinesummaryprice + stock+ ratingthenCombine()
- join()about 300 ms
thenCombine() merges results as they arrive, and join() blocks only once, at the end.The key is to create every future first and join last. Calling join() right after each supplyAsync() would make the code sequential again.
Approaches
Both approaches run the three calls on a pool of three threads. The first chains futures; the second hands a list of tasks to the executor.
Approach 1: CompletableFuture and thenCombine() (Recommended)
Idea: start each call with supplyAsync(task, pool), then merge the futures pairwise with thenCombine() and call join() once.
- Create a fixed pool with one thread per call.
- Start the three calls with
supplyAsync(); each returns at once. - Combine price and stock, then combine the result with rating.
- Call
join()on the final future and shut the pool down.
Time: O(max t) · Space: O(k). t is the time of one call and k the number of calls.
Approach 2: ExecutorService.invokeAll()
Idea: put the calls in a list of Callable tasks and pass it to invokeAll(), which returns when every task has finished.
- Build a
List<Callable<Object>>with one task per call. - Call
pool.invokeAll(tasks); it blocks until all are done. - Read each result with
get()in the same order as the tasks.
Time: O(max t) · Space: O(k).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Thread timing changes from run to run, so the programs print checks (true or false) instead of raw milliseconds; both tabs print the same output.
Approach 1: CompletableFuture and thenCombine() (Recommended)
Non-blocking until the very end, and easy to extend with exceptionally() or timeouts.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class ParallelCompletable {
static final AtomicInteger running = new AtomicInteger();
static final AtomicInteger maxRunning = new AtomicInteger();
// A fake remote call: 300 ms of "network time", while tracking how many calls overlap
static <T> T call(T value) {
maxRunning.accumulateAndGet(running.incrementAndGet(), Math::max);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
running.decrementAndGet();
return value;
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(3);
long start = System.nanoTime();
// Start all three calls first, then combine; nothing blocks until join()
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> call(499), pool);
CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> call(12), pool);
CompletableFuture<Double> rating = CompletableFuture.supplyAsync(() -> call(4.5), pool);
String summary = price
.thenCombine(stock, (p, s) -> "price=" + p + ", stock=" + s)
.thenCombine(rating, (ps, r) -> ps + ", rating=" + r)
.join();
long ms = (System.nanoTime() - start) / 1_000_000;
pool.shutdown();
System.out.println(summary);
System.out.println("calls running at the same time: " + maxRunning.get());
System.out.println("finished well under 900 ms: " + (ms < 800));
}
}
price=499, stock=12, rating=4.5 calls running at the same time: 3 finished well under 900 ms: true
Time complexity: O(max t) · Space complexity: O(k).
Approach 2: ExecutorService.invokeAll()
Simpler when you just need all results, but it blocks the calling thread and the results lose their types.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
public class ParallelInvokeAll {
static final AtomicInteger running = new AtomicInteger();
static final AtomicInteger maxRunning = new AtomicInteger();
static <T> T call(T value) {
maxRunning.accumulateAndGet(running.incrementAndGet(), Math::max);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
running.decrementAndGet();
return value;
}
// invokeAll() submits every task at once and returns when all are done
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
long start = System.nanoTime();
List<Callable<Object>> tasks = List.of(() -> call(499), () -> call(12), () -> call(4.5));
List<Future<Object>> results = pool.invokeAll(tasks);
String summary = "price=" + results.get(0).get() + ", stock=" + results.get(1).get()
+ ", rating=" + results.get(2).get();
long ms = (System.nanoTime() - start) / 1_000_000;
pool.shutdown();
System.out.println(summary);
System.out.println("calls running at the same time: " + maxRunning.get());
System.out.println("finished well under 900 ms: " + (ms < 800));
}
}
price=499, stock=12, rating=4.5 calls running at the same time: 3 finished well under 900 ms: true
Time complexity: O(max t) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| CompletableFuture and thenCombine() | O(max t) | O(k) |
| ExecutorService.invokeAll() | O(max t) | O(k) |
With one thread per call, the wall-clock time is the time of the slowest call instead of the sum of all calls. Memory grows only with the number of futures.
Interview Tips and Recommended Approach
- Start everything, then join. Joining inside the loop turns parallel code back into sequential code.
- Pass your own executor. The default common pool is shared and sized for CPU work, not for slow I/O.
- Know
allOf(). For a list of futures of the same type,CompletableFuture.allOf()waits for all of them. - Plan for failure. One failed future fails the combined one; add
exceptionally()or a timeout.
Recommended Approach: CompletableFuture and thenCombine()
Why: it keeps the results typed, blocks only once and leaves room for timeouts and fallbacks, which real service calls always need.