Concurrency · senior
CompletableFuture and virtual threads
Run parallel calls on a chosen executor with timeouts. Virtual threads make blocking cheap, but you still need limits, and on older JDKs synchronized pins the carrier thread.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Each call:
CompletableFuture.supplyAsync(() -> ..., executor). Without an executor it usesForkJoinPool.commonPool(), shared by the whole JVM and by parallel streams. Its parallelism is the CPU count minus one. - Optional parts:
completeOnTimeout(List.of(), 300, MILLISECONDS).exceptionally(ex -> List.of())(Java 9+). Required parts:orTimeout. Combine withthenCombine. - Timeouts do not stop the running work.
cancel(true)does not interrupt the task. The HTTP clients need their own timeouts.join()throws unchecked CompletionException;get()throws checked exceptions. - Copy MDC and trace context into tasks (a wrapping executor or Spring's TaskDecorator). Use a bounded executor per dependency (a bulkhead) and a circuit breaker.
- Virtual threads are final in Java 21. A platform thread is an OS thread with a big stack. A virtual thread is cheap; when it blocks on I/O, sleep or a java.util.concurrent lock, it unmounts and the carrier runs another.
- Do not pool virtual threads: one per task (
Executors.newVirtualThreadPerTaskExecutor()). Limit scarce resources with a Semaphore. - Pinning: on Java 21 to 23 blocking inside
synchronizedkept the carrier thread. JDK 24 (JEP 491) fixed that. Find pinning with JFR eventjdk.VirtualThreadPinned. - Without the old 200-thread limit, thousands of requests can reach a 30-connection pool and wait. Add a Semaphore or bulkhead sized to the pool and a short connection-wait timeout. CPU-bound work gains nothing from virtual threads. ThreadLocal works but each virtual thread has its own copy.
jcmd <pid> Thread.dump_to_file -format=json <file>includes virtual threads.
The red pen
Common traps: mistake → fix
Mistake: supplyAsync without an executor is safe
Fix: it uses the shared common pool, which slow tasks can fill.
Mistake: get(2, SECONDS) cancels the work
Fix: it only stops waiting.
Mistake: Virtual threads remove the need for limits
Fix: the old thread limit was also a throttle; add explicit limits.
Easy to hard
Questions interviewers ask, easy to hard
- Write a method that loads product, price and reviews in parallel, with reviews optional.
- Why did product pages time out when the offers service got slow?
- What are virtual threads and when would you not use them?
- Throughput fell after turning on virtual threads on Java 21. Why?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.