diff --git a/README.md b/README.md
index 8b577a2..665084c 100644
--- a/README.md
+++ b/README.md
@@ -35,6 +35,7 @@ article; each module's own README has that article's version table, quickstart,
| [`bufferedreader`](bufferedreader/) | Java BufferedReader: Read a File Line by Line (vs Scanner, Files.lines and readAllLines) |
| [`parallel-streams`](parallel-streams/) | Java Parallel Streams: When They're Slower (JMH Benchmarks and the Common Pool) |
| [`random`](random/) | Random vs ThreadLocalRandom vs SecureRandom vs RandomGenerator in Java |
+| [`completablefuture`](completablefuture/) | CompletableFuture in Java: thenApply vs thenCompose, allOf, Exceptions and Timeouts (and When Virtual Threads Win) |
## License
diff --git a/completablefuture/README.md b/completablefuture/README.md
new file mode 100644
index 0000000..8e4214e
--- /dev/null
+++ b/completablefuture/README.md
@@ -0,0 +1,76 @@
+# 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 | `25` |
+| Maven | 3.9.11 | |
+| Hardware | 2 vCPU x86-64 VM | So the common pool has parallelism 1 — see the notes below. |
+
+## Quickstart
+
+```bash
+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](../LICENSE).
diff --git a/completablefuture/output/01-thenapply-vs-thencompose.txt b/completablefuture/output/01-thenapply-vs-thencompose.txt
new file mode 100644
index 0000000..3f8fee6
--- /dev/null
+++ b/completablefuture/output/01-thenapply-vs-thencompose.txt
@@ -0,0 +1,11 @@
+== 1. thenApply with a function that itself returns a CompletableFuture
+nested.join() is a: CompletableFuture
+inner.join() is: Order[userId=1, item=laptop]
+
+== 2. thenCompose flattens it
+flat.join() is: Order[userId=1, item=laptop]
+
+== 3. Same three tools, measured (fixed pool of 4, so nothing queues)
+dependent calls: thenCompose (100 ms then 150 ms) -> Order[userId=1, item=laptop] 251 ms
+independent calls: start both, then thenCombine -> ankur + winter-sale 125 ms
+independent calls, wrongly chained with thenCompose -> ankur + winter-sale 221 ms
diff --git a/completablefuture/output/02-which-thread.txt b/completablefuture/output/02-which-thread.txt
new file mode 100644
index 0000000..fbf5550
--- /dev/null
+++ b/completablefuture/output/02-which-thread.txt
@@ -0,0 +1,17 @@
+availableProcessors = 2
+common pool parallelism = 1
+caller thread = main
+
+== Stage registered WHILE the previous stage is still running
+supplyAsync body ran on ForkJoinPool.commonPool-worker-1
+thenApply (registered before slow finished) ran on ForkJoinPool.commonPool-worker-1
+thenApplyAsync (no executor) ran on ForkJoinPool.commonPool-worker-1
+thenApplyAsync (executor = mine) ran on my-pool-1
+
+== Stage registered AFTER the previous stage finished
+thenApply (registered after slow finished) ran on main
+thenApply on completedFuture(..) ran on main
+
+== Supplying with your own executor
+supplyAsync(.., mine) body ran on my-pool-2
+thenApply after supplyAsync(.., mine) ran on my-pool-2
diff --git a/completablefuture/output/03-join-helps.txt b/completablefuture/output/03-join-helps.txt
new file mode 100644
index 0000000..2d18ec1
--- /dev/null
+++ b/completablefuture/output/03-join-helps.txt
@@ -0,0 +1,11 @@
+trials per loop: 200
+stage ran on main when main waited with join(): 37
+stage ran on main when main waited on a CountDownLatch: 0
+
+stack of the first stage that ran on main while it was inside join():
+ at com.ankurm.completablefuture.JoinHelpsDemo.lambda$main$1(JoinHelpsDemo.java:35)
+ at java.base/java.util.concurrent.CompletableFuture$UniAccept.tryFire(CompletableFuture.java:739)
+ at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:531)
+ at java.base/java.util.concurrent.CompletableFuture.waitingGet(CompletableFuture.java:1930)
+ at java.base/java.util.concurrent.CompletableFuture.join(CompletableFuture.java:2138)
+ at com.ankurm.completablefuture.JoinHelpsDemo.main(JoinHelpsDemo.java:39)
diff --git a/completablefuture/output/04-exception-handling.txt b/completablefuture/output/04-exception-handling.txt
new file mode 100644
index 0000000..31177bf
--- /dev/null
+++ b/completablefuture/output/04-exception-handling.txt
@@ -0,0 +1,23 @@
+== 1. What does exceptionally() receive?
+supplyAsync threw, exceptionally on same stage: CompletionException <- cause IllegalStateException: boom
+completeExceptionally(raw), same stage: IllegalStateException: boom
+completeExceptionally(raw), one stage later: CompletionException <- cause IllegalStateException: boom
+
+== 2. What do join() and get() throw?
+join(): CompletionException <- cause IllegalStateException: boom
+get(): ExecutionException <- cause IllegalStateException: boom
+state() = FAILED, exceptionNow() = IllegalStateException: boom
+
+== 3. exceptionally vs handle vs whenComplete
+exceptionally(ex -> -1) -> -1
+handle((v, ex) -> ex==null?v:-2) -> -2
+whenComplete saw: CompletionException <- cause IllegalStateException: boom
+whenComplete did not recover; join(): CompletionException <- cause IllegalStateException: boom
+
+== 4. On success, each one is a pass-through or a transformer
+exceptionally on success: 7
+handle on success: 14
+whenComplete on success: 7
+
+== 5. exceptionallyCompose: recover with another async call (JDK 12+)
+recovered value: 99
diff --git a/completablefuture/output/05-timeouts-and-cancel.txt b/completablefuture/output/05-timeouts-and-cancel.txt
new file mode 100644
index 0000000..e99d745
--- /dev/null
+++ b/completablefuture/output/05-timeouts-and-cancel.txt
@@ -0,0 +1,17 @@
+== 1. orTimeout: the future fails, the task keeps running
+join() after 100 ms: CompletionException <- cause TimeoutException: null
+task finished right after that? false
+task finished 700 ms later? true
+
+== 2. completeOnTimeout: a fallback value instead of an exception
+join() returned: fallback value
+
+== 3. cancel(true) does not interrupt the task either
+cancel(true) returned: true
+join(): CancellationException
+task saw an interrupt? false
+task ran to the end anyway? true
+
+== 4. The fix: keep the executor's Future and cancel THAT on timeout
+join(): CompletionException <- cause TimeoutException: null
+task saw an interrupt? true
diff --git a/completablefuture/output/06-allof-anyof.txt b/completablefuture/output/06-allof-anyof.txt
new file mode 100644
index 0000000..f3b205f
--- /dev/null
+++ b/completablefuture/output/06-allof-anyof.txt
@@ -0,0 +1,19 @@
+== 1. allOf returns CompletableFuture - you collect results yourself
+collected: [a, b, c]
+
+== 2. allOf with one early failure: it waits for the slow one anyway
+allOf failed with: CompletionException <- cause IllegalStateException: failed after 50 ms
+after 401 ms (the failure itself happened at 50 ms)
+slow task finished by then? true
+
+== 3. allOrFailFast: fail at the first failure, but nothing is cancelled
+failed with: CompletionException <- cause IllegalStateException: failed after 50 ms
+after 50 ms
+slow task finished by then? false
+slow task finished 450 ms later? true
+
+== 4. anyOf returns the first COMPLETION, and a failure counts
+anyOf failed with: CompletionException <- cause IllegalStateException: failed after 30 ms
+
+== 5. firstSuccess: skip failures, take the first value
+firstSuccess result: slow ok
diff --git a/completablefuture/output/07-virtual-threads-timings.txt b/completablefuture/output/07-virtual-threads-timings.txt
new file mode 100644
index 0000000..45b0e89
--- /dev/null
+++ b/completablefuture/output/07-virtual-threads-timings.txt
@@ -0,0 +1,14 @@
+availableProcessors = 2
+common pool parallelism = 1
+
+== Blocking work: 300 tasks, each sleeping 50 ms (a stand-in for a remote call)
+ default async pool (no executor argument) 15095 ms
+ fixed pool, 50 threads 309 ms
+ fixed pool, 200 threads 117 ms
+ virtual thread per task 62 ms
+
+== CPU-bound work: 16 tasks, each 2,000,000 rounds of SHA-256
+ sequential, one thread (baseline) 2237 ms
+ default async pool (no executor argument) 2159 ms
+ fixed pool, 2 threads (= cores) 1185 ms
+ virtual thread per task 1116 ms
diff --git a/completablefuture/output/08-structured-scope-without-preview.txt b/completablefuture/output/08-structured-scope-without-preview.txt
new file mode 100644
index 0000000..b434324
--- /dev/null
+++ b/completablefuture/output/08-structured-scope-without-preview.txt
@@ -0,0 +1,9 @@
+src/broken/StructuredScopeWithoutPreview.java:1: error: StructuredTaskScope is a preview API and is disabled by default.
+import java.util.concurrent.StructuredTaskScope;
+ ^
+ (use --enable-preview to enable preview APIs)
+src/broken/StructuredScopeWithoutPreview.java:11: error: StructuredTaskScope is a preview API and is disabled by default.
+ try (var scope = StructuredTaskScope.open()) {
+ ^
+ (use --enable-preview to enable preview APIs)
+2 errors
diff --git a/completablefuture/output/09-tests.txt b/completablefuture/output/09-tests.txt
new file mode 100644
index 0000000..75d7ee9
--- /dev/null
+++ b/completablefuture/output/09-tests.txt
@@ -0,0 +1,3 @@
+[INFO] Tests run: 26, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.421 s -- in com.ankurm.completablefuture.CompletableFutureContractTest
+[INFO] Tests run: 26, Failures: 0, Errors: 0, Skipped: 0
+[INFO] BUILD SUCCESS
diff --git a/completablefuture/pom.xml b/completablefuture/pom.xml
new file mode 100644
index 0000000..31666cf
--- /dev/null
+++ b/completablefuture/pom.xml
@@ -0,0 +1,43 @@
+
+
+ 4.0.0
+
+
+ com.ankurm
+ java-core-examples
+ 1.0
+
+
+ completablefuture
+ completablefuture
+ CompletableFuture in Java: thenApply vs thenCompose, which thread runs each stage, exception handling (exceptionally/handle/whenComplete), orTimeout/completeOnTimeout, allOf/anyOf, and a measured comparison with virtual threads.
+
+
+
+ org.junit.jupiter
+ junit-jupiter
+ 6.1.3
+ test
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+ 3.16.0
+
+ 25
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 3.6.1
+
+
+
+
diff --git a/completablefuture/scripts/compile-broken.sh b/completablefuture/scripts/compile-broken.sh
new file mode 100755
index 0000000..6811e89
--- /dev/null
+++ b/completablefuture/scripts/compile-broken.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+# Captures the compiler's own message for src/broken/StructuredScopeWithoutPreview.java.
+set -uo pipefail
+cd "$(dirname "$0")/.."
+mkdir -p output target/broken
+javac -d target/broken src/broken/StructuredScopeWithoutPreview.java 2>&1 \
+ | grep -v -e '^Picked up JAVA_TOOL_OPTIONS' -e '^Picked up _JAVA_OPTIONS' > output/08-structured-scope-without-preview.txt
+echo "==> 08-structured-scope-without-preview"
diff --git a/completablefuture/scripts/run-all.sh b/completablefuture/scripts/run-all.sh
new file mode 100755
index 0000000..21fc0ae
--- /dev/null
+++ b/completablefuture/scripts/run-all.sh
@@ -0,0 +1,18 @@
+#!/usr/bin/env bash
+# Regenerates every file in output/. Needs a JDK 25 on PATH (or JAVA_HOME set to one).
+# 03 (join counts) and 07 (timings) drift between runs and depend on core count: indicative only.
+set -euo pipefail
+cd "$(dirname "$0")/.."
+mvn -q -B compile 2>&1 | grep -v -e '^WARNING' -e '^Picked up' || true
+mkdir -p output
+run() { java -cp target/classes "com.ankurm.completablefuture.$1" 2>&1 | grep -v -e '^Picked up JAVA_TOOL_OPTIONS' -e '^Picked up _JAVA_OPTIONS' > "output/$2.txt"; echo "==> $2"; }
+run ThenApplyVsComposeDemo 01-thenapply-vs-thencompose
+run WhichThreadDemo 02-which-thread
+run JoinHelpsDemo 03-join-helps
+run ExceptionHandlingDemo 04-exception-handling
+run TimeoutDemo 05-timeouts-and-cancel
+run AllOfAnyOfDemo 06-allof-anyof
+run VirtualThreadsBenchmark 07-virtual-threads-timings
+./scripts/compile-broken.sh
+mvn -B test 2>&1 | grep -E 'Tests run:|BUILD|ERROR|FAIL' | grep -v 'Picked up' > output/09-tests.txt
+echo "regenerated:"; ls output
diff --git a/completablefuture/src/broken/StructuredScopeWithoutPreview.java b/completablefuture/src/broken/StructuredScopeWithoutPreview.java
new file mode 100644
index 0000000..3ed38ea
--- /dev/null
+++ b/completablefuture/src/broken/StructuredScopeWithoutPreview.java
@@ -0,0 +1,15 @@
+import java.util.concurrent.StructuredTaskScope;
+
+/**
+ * Deliberately NOT part of the build (it lives outside src/main). scripts/compile-broken.sh runs
+ * javac on it so the compiler's own message can be committed to output/.
+ *
+ * StructuredTaskScope is a preview API in JDK 25, so this fails without --enable-preview.
+ */
+public class StructuredScopeWithoutPreview {
+ public static void main(String[] args) throws Exception {
+ try (var scope = StructuredTaskScope.open()) {
+ scope.join();
+ }
+ }
+}
diff --git a/completablefuture/src/main/java/com/ankurm/completablefuture/AllOfAnyOfDemo.java b/completablefuture/src/main/java/com/ankurm/completablefuture/AllOfAnyOfDemo.java
new file mode 100644
index 0000000..f40d25a
--- /dev/null
+++ b/completablefuture/src/main/java/com/ankurm/completablefuture/AllOfAnyOfDemo.java
@@ -0,0 +1,125 @@
+package com.ankurm.completablefuture;
+
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static com.ankurm.completablefuture.Util.describe;
+import static com.ankurm.completablefuture.Util.sleep;
+
+/** allOf and anyOf: what they return, when they complete, and the two helpers you end up writing. */
+public class AllOfAnyOfDemo {
+
+ static CompletableFuture after(long ms, String value, ExecutorService pool) {
+ return CompletableFuture.supplyAsync(() -> {
+ sleep(ms);
+ return value;
+ }, pool);
+ }
+
+ static CompletableFuture failAfter(long ms, ExecutorService pool) {
+ return CompletableFuture.supplyAsync(() -> {
+ sleep(ms);
+ throw new IllegalStateException("failed after " + ms + " ms");
+ }, pool);
+ }
+
+ /** Completes as soon as ANY input fails; completes normally only when ALL succeed. */
+ static CompletableFuture allOrFailFast(List extends CompletableFuture>> futures) {
+ CompletableFuture result = new CompletableFuture<>();
+ futures.forEach(f -> f.whenComplete((v, ex) -> {
+ if (ex != null) {
+ result.completeExceptionally(ex);
+ }
+ }));
+ CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).thenRun(() -> result.complete(null));
+ return result;
+ }
+
+ /** Completes with the first SUCCESS; fails only if every input fails. */
+ static CompletableFuture firstSuccess(List> futures) {
+ CompletableFuture result = new CompletableFuture<>();
+ AtomicInteger failures = new AtomicInteger();
+ for (CompletableFuture f : futures) {
+ f.whenComplete((v, ex) -> {
+ if (ex == null) {
+ result.complete(v);
+ } else if (failures.incrementAndGet() == futures.size()) {
+ result.completeExceptionally(ex);
+ }
+ });
+ }
+ return result;
+ }
+
+ public static void main(String[] args) {
+ try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
+
+ System.out.println("== 1. allOf returns CompletableFuture - you collect results yourself");
+ CompletableFuture a = after(50, "a", pool);
+ CompletableFuture b = after(80, "b", pool);
+ CompletableFuture c = after(30, "c", pool);
+ CompletableFuture> all = CompletableFuture.allOf(a, b, c)
+ .thenApply(v -> List.of(a.join(), b.join(), c.join()));
+ System.out.println("collected: " + all.join());
+
+ System.out.println();
+ System.out.println("== 2. allOf with one early failure: it waits for the slow one anyway");
+ AtomicBoolean slowDone = new AtomicBoolean();
+ CompletableFuture early = failAfter(50, pool);
+ CompletableFuture slow = CompletableFuture.supplyAsync(() -> {
+ sleep(400);
+ slowDone.set(true);
+ return "slow ok";
+ }, pool);
+ long t0 = System.nanoTime();
+ try {
+ CompletableFuture.allOf(early, slow).join();
+ } catch (CompletionException e) {
+ long ms = (System.nanoTime() - t0) / 1_000_000;
+ System.out.println("allOf failed with: " + describe(e));
+ System.out.println("after " + ms + " ms (the failure itself happened at 50 ms)");
+ System.out.println("slow task finished by then? " + slowDone.get());
+ }
+
+ System.out.println();
+ System.out.println("== 3. allOrFailFast: fail at the first failure, but nothing is cancelled");
+ AtomicBoolean slow2Done = new AtomicBoolean();
+ CompletableFuture early2 = failAfter(50, pool);
+ CompletableFuture slow2 = CompletableFuture.supplyAsync(() -> {
+ sleep(400);
+ slow2Done.set(true);
+ return "slow ok";
+ }, pool);
+ long t1 = System.nanoTime();
+ try {
+ allOrFailFast(List.of(early2, slow2)).join();
+ } catch (CompletionException e) {
+ long ms = (System.nanoTime() - t1) / 1_000_000;
+ System.out.println("failed with: " + describe(e));
+ System.out.println("after " + ms + " ms");
+ System.out.println("slow task finished by then? " + slow2Done.get());
+ }
+ sleep(450);
+ System.out.println("slow task finished 450 ms later? " + slow2Done.get());
+
+ System.out.println();
+ System.out.println("== 4. anyOf returns the first COMPLETION, and a failure counts");
+ CompletableFuture