completablefuture: CompletableFuture module (thenApply vs thenCompose and the serial trap, which thread runs a stage incl. join() running dependents, CompletionException wrapping, orTimeout/cancel not stopping work, allOf/anyOf with fail-fast and first-success helpers, virtual-thread timings, StructuredTaskScope preview error), 26 contract tests

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b3dRuKRhrHFPzWSSxr
This commit is contained in:
Ankur Mhatre
2026-11-22 18:56:47 +05:30
co-authored by Claude Sonnet 5.5
parent 59a5435825
commit 9c2ae10d7f
25 changed files with 1335 additions and 0 deletions
@@ -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
@@ -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
@@ -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)
@@ -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
@@ -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
@@ -0,0 +1,19 @@
== 1. allOf returns CompletableFuture<Void> - 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
@@ -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
@@ -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
+3
View File
@@ -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