CompletableFuture Composition
As a Tech Lead engineer, explain CompletableFuture Composition. What problem does it solve and how would you describe it in an interview?
Answers use simple, clear English.
Quick interview answer
At Tech Lead depth: start with the problem, then mechanism, then a short example. supplyAsync runs async task; thenApply transforms; thenCompose flattens nested futures; allOf waits for batch.
Detailed answer
At Tech Lead depth: start with the problem, then mechanism, then a short example. supplyAsync runs async task; thenApply transforms; thenCompose flattens nested futures; allOf waits for batch. Exceptionally/handle for error paths. Core: supplyAsync runs async task; thenApply transforms; thenCompose flattens nested futures; allOf waits for batch. Exceptionally/handle for error paths. Real-time example: Aggregate microservice responses: CompletableFuture.allOf(userF, ordersF).thenApply(...). Pros: Composable async without raw callbacks; integrates with thread pools. Cons: Default ForkJoinPool.commonPool() shared — inject Executor for isolation. Common mistakes: Blocking get() on async chain in request thread; lost exceptions without handle. Best practices: Specify executor for IO; use orTimeout/join with timeout in Java 9+. Audience level: Tech Lead.
Full explanation
supplyAsync runs async task; thenApply transforms; thenCompose flattens nested futures; allOf waits for batch. Exceptionally/handle for error paths.
Real example & use case
Aggregate microservice responses: CompletableFuture.allOf(userF, ordersF).thenApply(...).
Pros & cons
Pros: Composable async without raw callbacks; integrates with thread pools. Cons: Default ForkJoinPool.commonPool() shared — inject Executor for isolation.
Common mistakes
Blocking get() on async chain in request thread; lost exceptions without handle.
Best practices
Specify executor for IO; use orTimeout/join with timeout in Java 9+.
Follow-up questions
- How would you test CompletableFuture Composition?
- What metrics prove CompletableFuture Composition is healthy in prod?
- How does CompletableFuture Composition change at 10× traffic?