Java Materials
← Core Java · Chapter 16

CompletableFuture, Fork/Join and parallelism

Future models a pending result and supports blocking get and cancellation. CompletionStage models dependent work. CompletableFuture implements both. Use runAsync for side effects and supplyAsync for values. Choose an explicit executor for blocking I/O to protect common-pool workers.

Building dependency graphs

Definition:

A CompletionStage graph expresses which asynchronous outcomes depend on others.

Explanation:

thenApply is a synchronous transformation of a successful value, thenCompose flattens a dependent stage, and thenCombine joins independent successful stages.

Illustration image:

Building dependency graphs. User lookup · User ID available · Order lookup · Extract statusBuilding dependency graphsSource or actorUser lookupFirst boundaryUser ID availableInspected stateOrder lookupObservable effectExtract status
User lookup · User ID available · Order lookup · Extract status

Example:

Worked Java example · see surrounding context in notes
var user = java.util.concurrent.CompletableFuture.supplyAsync(api::loadUser, ioPool);
var order = user.thenCompose(u -> api.loadOrderAsync(u.id()));
return order.thenApply(Order::status);

Expected behavior. The order call begins after the user ID exists and the result remains a single completion stage.

Internal working:

A non-Async continuation may execute on the thread completing its parent. Keep expensive or blocking continuations away from request threads and event loops unless the execution placement is intentional.

Interview questions:

When should thenCompose replace thenApply?

Use thenCompose when the callback returns a stage and the caller needs its eventual result without nested stages.

Failure policy and cancellation

Definition:

An aggregate deadline bounds how long a caller waits for several asynchronous outcomes.

Explanation:

allOf reports completion without collecting individual results. anyOf can return a failure if that finishes first.

Illustration image:

Failure policy and cancellation. Profile required · Balance required · Rewards optional · Deadline and resultFailure policy and cancellationSource or actorProfile requiredFirst boundaryBalance requiredInspected stateRewards optionalObservable effectDeadline and result
Profile required · Balance required · Rewards optional · Deadline and result

Example:

Worked Java example · see surrounding context in notes
var safeRewards = rewards.exceptionally(error -> "unavailable");
return java.util.concurrent.CompletableFuture.allOf(profile, balance, safeRewards)
    .orTimeout(800, java.util.concurrent.TimeUnit.MILLISECONDS)
    .thenApply(ignored -> java.util.List.of(profile.join(), balance.join(), safeRewards.join()));

Expected behavior. Only rewards has an explicit fallback. Required failures remain exceptional.

Internal working:

Recover optional failures on their own stage before combining and keep required failures visible. orTimeout limits future completion, not underlying socket activity. Configure client deadlines and decide whether retries are safe.

Interview questions:

Does orTimeout stop a blocking HTTP client call?

It completes the future exceptionally. Configure the transport’s own I/O timeout or cancellation behavior.

Fork/Join, common-pool contention and thresholds

Definition:

Fork/Join executes divisible work using local task queues and work stealing.

Explanation:

ForkJoinPool is optimized for recursively divisible tasks.

Illustration image:

Fork/Join, common-pool contention and thresholds. Root task · Split task A · Split task B · Combine totalsFork/Join, common-pool contention and thresholdsSource or actorRoot taskFirst boundarySplit task AInspected stateSplit task BObservable effectCombine totals
Root task · Split task A · Split task B · Combine totals

Example:

Worked Java example · see surrounding context in notes
long count = java.util.stream.LongStream.range(0, 1_000_000)
    .parallel().filter(value -> (value & 1) == 0).count();
System.out.println(count);

Expected behavior. Prints 500000. The result is independent of partition boundaries because the predicate is pure and counting is associative.

Internal working:

Too-fine splits cost more scheduling than computation, while too-large splits reduce parallelism. Blocking I/O inside common-pool tasks can slow unrelated features. Measure a representative workload with an explicit benchmark before choosing parallel streams over sequential work.

Interview questions:

What makes a good split threshold?

Make subproblems large enough to pay for scheduling but small enough to distribute the work. Measure on representative data.

Reference subtopics

Composition and execution placement

thenApply maps a value; thenCompose flattens a dependent asynchronous result; thenCombine merges two independent results. Non-Async continuations may run in the completing thread or the thread attaching a stage when already completed. Async variants without an executor generally use the common pool under ordinary configurations.

Failure aggregation and completion

allOf waits for all stages, propagates exceptional completion, and returns no collected values. anyOf returns the first completion, which can be exceptional. exceptionally recovers on failure, handle transforms either outcome and whenComplete observes it. get reports checked failures; join wraps failures in unchecked CompletionException.

Timeout and cancellation semantics

orTimeout and completeOnTimeout arrived in Java 9. The former completes exceptionally; the latter fills a fallback. Neither automatically interrupts network work. Keep deadlines at the client boundary and define whether partial results are legal. CompletableFuture.cancel uses exceptional completion; do not assume it drives a worker interrupt.

Fork/Join and parallel streams

ForkJoinPool workers steal tasks. RecursiveTask produces a result and RecursiveAction has no value. Choose a split threshold large enough to amortize overhead. Blocking or shared mutable state can wipe out gains in parallel streams and contend with other users of the common pool. Compare with a sequential baseline under realistic load.

Run the complete Java labs ↗ · Java reference ↗