Modern Java Concurrency: Key Takeaways and an Adoption Checklist
The whole course in one place: what virtual threads, structured concurrency and scoped values each replace, how they fit together in one request, a release timeline from Java 19 to 28, a problem-to-tool cheat sheet, common myths, and an adoption checklist.
kvi5hnuCode Sprout team member8 min readOn this page
This course started with a trip-quote service that needed one platform thread for every waiting request, and the workarounds that followed: pools, CompletableFuture chains, reactive pipelines. Since then, Java has gained three features that, together, let you write that service as plain sequential code that still scales:
| Feature | Replaces | Status |
|---|---|---|
| Virtual threads (Part 2, 3) | thread pools sized for waiting, asynchronous code written only to avoid blocking | final since Java 21; no synchronized pinning since 24 |
| Structured concurrency (Part 4) | ad-hoc Future and CompletableFuture fan-out, manual cancellation | preview in 21 to 27, final in Java 28 |
| Scoped values (Part 5) | ThreadLocal for request context, parameters passed only to be passed on | final since Java 25 |

All three in one request
This program prices a six-leg trip. It uses each feature for what it's best at, and the earlier lessons about limits. It uses the Java 27 preview API (java --enable-preview TripQuotes.java), which Java 28 makes final.
import java.time.Duration;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Joiner;
import java.util.concurrent.StructuredTaskScope.Subtask;
import java.util.concurrent.atomic.AtomicInteger;
// Java 27 preview API (java --enable-preview TripQuotes.java); final in Java 28
public class TripQuotes {
record RequestContext(String requestId, String customer) {}
static final ScopedValue<RequestContext> REQUEST = ScopedValue.newInstance(); // implicit, immutable context
static final Semaphore PARTNER = new Semaphore(3); // the partner allows 3 calls at once
static final AtomicInteger inPartner = new AtomicInteger();
static final AtomicInteger maxInPartner = new AtomicInteger();
static final Set<String> requestIdsSeen = ConcurrentHashMap.newKeySet();
static int flight(String route) throws InterruptedException {
PARTNER.acquire(); // bound the shared resource explicitly
try {
maxInPartner.accumulateAndGet(inPartner.incrementAndGet(), Math::max);
requestIdsSeen.add(REQUEST.get().requestId()); // the context reached the subtask
Thread.sleep(100); // blocking I/O: cheap on a virtual thread
return 100 + route.chars().sum() % 400;
} finally {
inPartner.decrementAndGet();
PARTNER.release();
}
}
static int hotel(String route) throws InterruptedException {
Thread.sleep(route.endsWith("TOS") ? 2_000 : 120); // the Tromsø hotel system is very slow today
return 95;
}
static String quote(String route) throws InterruptedException {
try (var scope = StructuredTaskScope.open(cf -> cf.withTimeout(Duration.ofMillis(800)))) {
Subtask<Integer> flight = scope.fork(() -> flight(route));
Subtask<Integer> hotel = scope.fork(() -> hotel(route));
scope.join(); // both, or the first failure, or the deadline
return route + " " + (flight.get() + 3 * hotel.get());
} catch (ExecutionException e) {
return route + " no quote ("
+ (e.getCause() instanceof StructuredTaskScope.CancelledByTimeoutException ? "too slow" : e.getCause().getMessage())
+ ")";
}
}
static List<String> trip(List<String> routes) throws Exception {
try (var scope = StructuredTaskScope.open(Joiner.<String>allSuccessfulOrThrow())) {
for (String route : routes) scope.fork(() -> quote(route)); // a nested scope per route
return scope.join();
}
}
public static void main(String[] args) throws Exception {
List<String> routes = List.of("LIS-OSL", "OPO-OSL", "FAO-OSL", "LIS-BGO", "OSL-TOS", "LIS-SVG");
long start = System.nanoTime();
List<String> quotes = ScopedValue.where(REQUEST, new RequestContext("req-7", "ana"))
.call(() -> trip(routes));
long millis = (System.nanoTime() - start) / 1_000_000;
quotes.forEach(q -> System.out.println(" " + q));
System.out.println("partner calls at once, at most: " + maxInPartner.get());
System.out.println("request ids seen by subtasks: " + requestIdsSeen);
System.out.println("whole trip answered " + (millis < 1_200 ? "within the deadline (under 1.2 s)" : "late: " + millis + " ms"));
System.out.println("context outside the binding: bound = " + REQUEST.isBound());
}
}
Output:
LIS-OSL 500
OPO-OSL 506
FAO-OSL 482
LIS-BGO 478
OSL-TOS no quote (too slow)
LIS-SVG 502
partner calls at once, at most: 3
request ids seen by subtasks: [req-7]
whole trip answered within the deadline (under 1.2 s)
context outside the binding: bound = false
What each part contributes:
- Virtual threads run every subtask: 12 subtasks blocked at once (6 hotel calls, 3 flight calls and 3 waiting for a permit), written as
Thread.sleepand plain return values (articles 8 to 11). - Structured concurrency gives the code its shape. The outer scope owns one subtask per route, and each route's inner scope owns its flight and hotel calls (article 35). Nothing outlives
trip(). - A deadline per quote. The slow Tromsø hotel hit the 800 ms timeout. Its scope cancelled both its subtasks, and
quoteturned theCancelledByTimeoutExceptioninto a fallback (articles 31 and 32). The other five quotes were unaffected, and the whole trip was answered within the deadline. - A semaphore kept the partner at its limit of three concurrent calls, although six flight lookups wanted to run at once (article 12). Virtual threads remove the implicit limits of thread pools, so the limits you need must be explicit.
- A scoped value carried the request ID into every subtask, two scope levels down, without a parameter (article 41). Outside the
where(...).call(...), it's unbound again: no cleanup, no leaks.
Cheat sheet: problem to tool
| Problem | Tool | Article |
|---|---|---|
| Many concurrent requests that mostly wait for I/O | a virtual thread per task: newVirtualThreadPerTaskExecutor(), or the framework switch | 9, 48, 49 |
| CPU-bound work | parallel streams, ForkJoinPool, or a pool sized to the cores | 6, 22 |
| Limit concurrency towards a database or partner | Semaphore, connection pool size, bulkhead | 12 |
| Run related subtasks, fail fast, cancel the rest | StructuredTaskScope with allSuccessfulOrThrow() | 28, 29 |
| Take the first success: replicas, hedged requests | Joiner.anySuccessfulOrThrow() | 30 |
| Custom completion rules: quorum, best-effort | a custom Joiner | 33 |
| Deadline for a group of calls | withTimeout on the scope's configuration | 32 |
| Request context: user, trace ID, tenant | ScopedValue bound with where(...).run/call | 40, 41 |
| Locks around blocking I/O on Java 21 to 23 | ReentrantLock instead of synchronized | 13 |
| Which virtual threads exist, and what they're waiting for | jcmd <pid> Thread.dump_to_file -format=json | 17, 36 |
| Pinning and scheduling problems | JFR jdk.VirtualThreadPinned, jdk.VirtualThreadSubmitFailed | 16 |
| Stream processing: merge, window, sample, backpressure | a reactive library | 46, 47 |
Myths, corrected
- "Virtual threads are faster." A single request isn't any faster. Virtual threads let far more requests wait at the same time, so throughput rises for I/O-bound work (Little's law, article 10). CPU-bound work gains nothing.
- "Pool virtual threads to reuse them." Don't. They're cheap to create, and a pool brings back the limits and thread-local leaks you wanted to avoid. Limit the resource, not the threads.
- "Virtual threads make limits unnecessary." The opposite: thread pools were silent limits, and now databases and partners need explicit ones.
- "
ThreadLocaldoesn't work with virtual threads." It works, but millions of short-lived threads each create their own copy. Use scoped values for context and avoid thread-local caches (articles 15 and 39). - "
synchronizedalways pins." Only on Java 21 to 23. Java 24 fixed it (JEP 491). Native frames and class initialization can still pin (article 14). - "Reactive programming is obsolete." For request/response services, mostly yes. For event-stream processing with operators and backpressure, it's still the better tool (article 47).
Adoption checklist
- Pick the JDK. Java 25 (LTS) has final virtual threads and scoped values and no
synchronizedpinning. On Java 21, check for pinning and preferReentrantLockaround blocking calls. - Turn on virtual threads in one service: the framework switch (
spring.threads.virtual.enabled,@RunOnVirtualThread,@ExecuteOn(TaskExecutors.BLOCKING)) ornewVirtualThreadPerTaskExecutor(). - Set limits explicitly: connection pool sizes, semaphores or bulkheads in front of partners, and
maxAsyncorconcurrency-limitfor asynchronous work. - Remove thread pooling for I/O-bound work. Keep bounded platform pools for CPU-bound work.
- Audit
ThreadLocals: caches of expensive objects, and context that should become aScopedValue. - Keep the event loops free in reactive or event-loop frameworks: blocking calls belong on virtual threads.
- Monitor: JSON thread dumps, JFR pinning events, connection pool wait times and downstream latency, which is where the waiting has moved.
- Load test before and after, with realistic downstream latency, and roll out service by service.
- Adopt structured concurrency for fan-out code as soon as you're on Java 28, or try the preview on Java 27, whose API Java 28 makes final unchanged. The Java 25 and 26 previews differ from it.
What's current
- Java 25 (September 2025, LTS) is the first LTS with final virtual threads without
synchronizedpinning, and final scoped values. - Java 27 (September 2026) has the seventh, last preview of structured concurrency (JEP 533). Java 28 (March 2027) makes it final (JEP 543) without API changes.
- Spring Boot, Quarkus, Micronaut, Helidon and Jakarta EE all support virtual threads (articles 48 and 49). Libraries continue to replace
synchronizedaround I/O and thread-local caches, although both matter less on current JDKs.
Common questions
Which Java version should a new service start on? Java 25, the current LTS release. It has everything in this course except final structured concurrency. If you need structured concurrency without preview flags, plan for Java 28 or the next LTS release.
Do I need to rewrite code to benefit from virtual threads? Usually not. Blocking code that ran on a thread pool runs unchanged on virtual threads. What needs work is around it: limits, thread-local caches, CPU-heavy tasks and, on Java 21 to 23, pinning.
Where should a team start learning? With virtual threads (Part 2) and limits (article 12), because that's what changes production behavior. Then structured concurrency for fan-out code, and scoped values when replacing thread-local context.
Summary
- Virtual threads make blocking cheap, structured concurrency gives concurrent subtasks a scope with clear ownership, failure and cancellation, and scoped values pass immutable context down that scope.
- Together, they let I/O-bound services be written as sequential code that scales, with stack traces, debuggers and thread dumps that make sense.
- Limits move from thread pools to the resources themselves: pools, semaphores and bulkheads.
- Reactive libraries remain the tool for event streams, and bounded platform pools for CPU-bound work.
- Java 25 is the LTS baseline for virtual threads and scoped values. Structured concurrency is final in Java 28.
Practice questions
In TripQuotes, what would change if the semaphore were removed?
Answer
All six flight lookups would call the partner at once, so the partner would see six concurrent calls instead of at most three. In this demo, the trip would finish a little sooner. Against a real partner with a limit of three, the extra calls would be rejected or throttled, and could cause errors. The thread count doesn't limit anything any more: only the semaphore does.
Why did the slow Tromsø hotel not delay the other five quotes, or the whole trip beyond about 800 ms?
Answer
Each route has its own inner scope with its own 800 ms deadline. Only the Tromsø scope timed out: it cancelled its two subtasks, and quote returned a fallback. The outer scope sees six successful subtasks, since quote never throws, and it completes as soon as the slowest of them finishes, at about the deadline.
A team on Java 21 enables virtual threads, and throughput drops under load. Thread dumps show many virtual threads waiting while all carriers are busy inside a logging library. What's the likely cause, and the options?
Answer
Pinning: the library blocks for I/O inside synchronized, which on Java 21 holds the carrier, and with every carrier pinned, other virtual threads can't run. The options: upgrade to Java 24 or later (JEP 491), where synchronized no longer pins, upgrade the library to a version that uses ReentrantLock, or make logging asynchronous. JFR's jdk.VirtualThreadPinned events confirm the diagnosis.
Review quiz
You've finished Part 7: Frameworks and Takeaways, and the whole course. Test yourself with the Part 7 review quiz, which covers Spring Boot, Quarkus, Micronaut, Helidon, Jakarta EE and the adoption checklist.
Then put the whole course together with the final quizzes:
- Modern Java Concurrency Final Exam: 30 questions across all seven parts.
- Java Concurrency Interview Questions: the questions interviewers ask about threads, virtual threads, structured concurrency and scoped values.
- Java Concurrency's Delicate Details: edge cases that surprise experienced developers.
- Java Concurrency, Java 21 to 28: what changed in each release.
Previous: Virtual Threads in Quarkus, Jakarta EE, Helidon and Micronaut
Next: Modern Java Concurrency Course: Full Outline and Reading Order

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.