CompletableFuture models asynchronous completion and composition. Error-handling stages can recover, transform or observe failure with different semantics.
Before you start
You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.
The practical goal is to reason through this situation: ThenCompose flattens dependent asynchronous operations; an error stage maps a known failure to a fallback. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Compose dependent work
ThenCompose combines stages when the next operation already returns a future.
Step 2: Choose error semantics
Observation, recovery and transformation are distinct; recover only known failures.
Step 3: Avoid blocking composition
Joining inside each stage can tie up execution capacity and obscure asynchronous flow.
Worked scenario
ThenCompose flattens dependent asynchronous operations; an error stage maps a known failure to a fallback.
A user lookup completes, then an account lookup returns another future. ThenApply would produce a nested future; thenCompose produces one completion chain. Recovering every exception with an empty account masks outages and bugs, so keep unexpected failures exceptional with their context retained.
Common mistake
Blocking join inside every stage can defeat asynchronous composition.
Verify the behavior
Test success, first-stage failure, second-stage failure and documented fallback behavior.
Interview exercise
Preserve unexpected failures.
Answer and reasoning
Recover only documented failures and propagate others, retaining context and a clear cancellation policy.
Continue learning
Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.