Java 8: Call three slow services and combine the results. Compare sequential, Future and CompletableFuture solutions.
Problem
A product page needs price, stock and reviews from three services that each take about 300 ms. Build the page as fast as possible, and survive a slow or failing service.
import java.util.concurrent.ThreadLocalRandom;
final class Services {
static void pause(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
static int price(String sku) { pause(300); return 999; }
static int stock(String sku) { pause(300); return 42; }
static String reviews(String sku) { pause(300); return "4.6 stars"; }
static String flakyReviews(String sku) {
pause(100);
if (ThreadLocalRandom.current().nextBoolean()) throw new IllegalStateException("reviews down");
return "4.6 stars";
}
}Approach 1: Sequential calls (feasible, ~900 ms)
Simple, but latency is the sum of all calls.
class PageSequential {
static String build(String sku) {
return Services.price(sku) + " | " + Services.stock(sku) + " | " + Services.reviews(sku);
}
}Approach 2: ExecutorService + Future (Java 5, ~300 ms)
Calls run in parallel, but Future.get() blocks the caller and there is no way to compose or chain results without blocking.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
class PageFutures {
static String build(String sku, ExecutorService pool) throws Exception {
Future<Integer> price = pool.submit(() -> Services.price(sku));
Future<Integer> stock = pool.submit(() -> Services.stock(sku));
Future<String> reviews = pool.submit(() -> Services.reviews(sku));
return price.get() + " | " + stock.get() + " | " + reviews.get(); // blocks three times
}
}Approach 3: CompletableFuture composition (Java 8, ~300 ms, non-blocking)
supplyAsync starts each call; thenCombine merges results as they complete. Always pass a dedicated executor for I/O instead of the common ForkJoinPool.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
class PageCompletable {
static CompletableFuture<String> build(String sku, Executor io) {
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> Services.price(sku), io);
CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> Services.stock(sku), io);
CompletableFuture<String> reviews = CompletableFuture.supplyAsync(() -> Services.reviews(sku), io);
return price.thenCombine(stock, (p, s) -> p + " | " + s)
.thenCombine(reviews, (ps, r) -> ps + " | " + r);
}
}Approach 4: Resilient version with fallbacks and timeouts (Java 8 + Java 9 timeout APIs)
A failing or slow optional service should degrade the page, not break it. exceptionally supplies a fallback; Java 9's completeOnTimeout caps waiting time (in Java 8 you would schedule a timeout yourself).
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
class PageResilient {
static CompletableFuture<String> build(String sku, Executor io) {
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> Services.price(sku), io);
CompletableFuture<Integer> stock = CompletableFuture.supplyAsync(() -> Services.stock(sku), io)
.completeOnTimeout(-1, 500, TimeUnit.MILLISECONDS); // Java 9+
CompletableFuture<String> reviews = CompletableFuture.supplyAsync(() -> Services.flakyReviews(sku), io)
.exceptionally(ex -> "reviews unavailable"); // Java 8 fallback
return CompletableFuture.allOf(price, stock, reviews)
.thenApply(v -> price.join() + " | " + (stock.join() < 0 ? "stock unknown" : stock.join()) + " | " + reviews.join());
}
}Run all approaches
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class PageDemo {
public static void main(String[] args) throws Exception {
ExecutorService io = Executors.newFixedThreadPool(8);
try {
long t = System.nanoTime();
System.out.println(PageSequential.build("sku-1") + " in " + ms(t) + " ms"); // ~900 ms
t = System.nanoTime();
System.out.println(PageFutures.build("sku-1", io) + " in " + ms(t) + " ms"); // ~300 ms
t = System.nanoTime();
System.out.println(PageCompletable.build("sku-1", io).join() + " in " + ms(t) + " ms");
t = System.nanoTime();
System.out.println(PageResilient.build("sku-1", io).join() + " in " + ms(t) + " ms");
} finally {
io.shutdown();
}
}
static long ms(long start) { return (System.nanoTime() - start) / 1_000_000; }
}Feasible → optimal
- Sequential: latency = sum of calls (900 ms).
Future: latency = slowest call (300 ms), but blocking and hard to compose.CompletableFuture: same latency, non-blocking composition, the Java 8 answer.- With fallbacks and timeouts: production-grade, because the page latency is bounded and one failure does not fail the page. On Java 21, virtual threads make Approach 2's blocking style cheap again (see the Java 21 questions).
Follow-up questions interviewers ask
Try answering each one before you open it.
Why should you avoid the default common ForkJoinPool for these calls?
supplyAsync without an executor uses ForkJoinPool.commonPool(), sized to CPU cores minus one and shared by the whole JVM (parallel streams use it too). Blocking I/O inside it starves every other user of the pool and caps concurrency at a handful of calls. Use a dedicated, bounded executor for I/O, or a virtual-thread executor on Java 21.
What is the difference between thenApply, thenCompose and thenCombine?
thenApply transforms the result synchronously (map). thenCompose chains another asynchronous call that depends on the result and flattens the nested future (flatMap): getUser(id).thenCompose(u -> getOrders(u)). thenCombine joins two independent futures when both complete.