Files
..

completablefuture

Companion code for the ankurm.com post "CompletableFuture in Java: thenApply vs thenCompose, allOf, Exceptions and Timeouts (and When Virtual Threads Win)" — https://ankurm.com/java-completablefuture-thenapply-thencompose-allof-timeouts/ . Thirty-first module in java-core-examples, the Java-core / concurrency series.

The post is the only documentation: every explanation, diagram and deeper-dive section lives there, and each code block in it links to a file in this module. There is deliberately no docs/ folder.

Seven demos, each isolating one thing people get wrong about CompletableFuture: thenApply vs thenCompose (and the serial-by-accident trap), which thread runs each stage, the way join() can run your stage on the waiting thread, what exceptionally / handle / whenComplete actually receive, why orTimeout and cancel(true) do not stop the work, how allOf / anyOf behave when something fails, and a measured comparison against virtual threads.

Versions this was built and tested against

Component Version Notes
JDK 25.0.5.1+2 (Temurin, LTS) Every demo runs on one JDK.
JUnit Jupiter 6.1.3 Latest GA on Maven Central at the time of writing.
maven-surefire-plugin 3.6.1
maven-compiler-plugin 3.16.0 <release>25</release>
Maven 3.9.11
Hardware 2 vCPU x86-64 VM So the common pool has parallelism 1 — see the notes below.

Quickstart

export JAVA_HOME=/path/to/jdk-25
mvn package
java -cp target/classes com.ankurm.completablefuture.ThenApplyVsComposeDemo
java -cp target/classes com.ankurm.completablefuture.VirtualThreadsBenchmark

scripts/run-all.sh regenerates every file in output/ (needs a JDK 25 on PATH).

What's in here

File What it shows
.../ThenApplyVsComposeDemo.java thenApply with a future-returning function nests the future; thenCompose flattens it; independent calls chained with thenCompose run serially (221 ms vs 125 ms with thenCombine).
.../WhichThreadDemo.java A stage runs on the completing thread if registered before completion, and on the caller if registered after. ...Async moves it to the async pool or your executor.
.../JoinHelpsDemo.java A thread blocked in join() on the source future can run the dependent stage itself. Waiting on a CountDownLatch instead never does.
.../ExceptionHandlingDemo.java The CompletionException wrapper: when exceptionally sees it raw and when wrapped; join() vs get(); handle vs whenComplete; exceptionallyCompose.
.../TimeoutDemo.java orTimeout / completeOnTimeout complete the future, not the task. cancel(true) does not interrupt. The fix: cancel the executor's own Future.
.../AllOfAnyOfDemo.java allOf is Void and waits for the slowest even after a failure; allOrFailFast and firstSuccess helpers; anyOf counts a failure as a win.
.../VirtualThreadsBenchmark.java 300 blocking tasks and 16 CPU-bound tasks across the default pool, fixed pools and a virtual-thread executor.
src/broken/StructuredScopeWithoutPreview.java Not compiled by Maven. scripts/compile-broken.sh captures javac's message: StructuredTaskScope is a preview API on JDK 25.
src/test/.../CompletableFutureContractTest.java 26 tests pinning every deterministic behaviour the post states. Timing assertions check shape, not exact milliseconds.
output/01-07 Each demo's real run.
output/08 The compiler message for the preview-API failure.
output/09 JUnit summary.

Reading the results honestly (2-vCPU sandbox)

The default-pool row in output/07 is a sandbox artefact, and also a real warning. With 2 cores the common pool's parallelism is 1 (the default is max(1, cores - 1)), so 300 tasks sleeping 50 ms took 15,095 ms: 300 x 50 ms, one after another. On an 8-core machine the same code would have 7 workers and take roughly a seventh of that. The lesson survives the hardware: the common pool is sized for CPU work, and a blocking task occupies a worker for its whole sleep.

Virtual threads do not make CPU-bound work faster. In the CPU-bound block a fixed pool of 2 threads (= cores) took 1,185 ms and a virtual-thread executor 1,116 ms. Both are bounded by 2 cores; treat that gap as noise, not a result: it flipped sign between earlier runs.

output/03 varies from run to run, on purpose. How often join() runs the stage on the waiting thread depends on a race between that thread and the worker. Across the runs made while writing the post the count ranged from 8 to 104 of 200 (37 in the committed run); the latch loop was 0 every time.

Timing figures drift between runs. Everything except the ordering of the rows (virtual < fixed 200 < fixed 50 << default pool for blocking work) should be read as indicative.

License

MIT - see the repo-wide LICENSE.