Migrating to Java Virtual Threads: A Practical Checklist
A step-by-step plan for moving an existing Java service to virtual threads: upgrade, inspect for pinning and thread-local caches, switch executors, replace the old pool's accidental limits with explicit ones, load test and roll out. With a measured before-and-after example.
kvi5hnuCode Sprout team member9 min readOn this page
Part 2 covered what virtual threads are, how they work, and where they fall short. This article turns that into a plan for an existing service. The good news is that migration is usually small in code: often a single executor or one framework setting. The care goes into what surrounds that change.

1. Upgrade the JDK and libraries
- Use Java 25 LTS, or at least Java 24. Virtual threads work on Java 21, but
synchronizedpins there (article 13), and many libraries still block insidesynchronized. Java 24's JEP 491 removed that problem. - Upgrade dependencies. JDBC drivers, HTTP clients, connection pools, logging frameworks and web servers have all released versions that work better with virtual threads, mostly by replacing long
synchronizedsections and thread-local caches. Check release notes for "virtual threads" or "Loom". - Upgrade tooling. Profilers, APM agents and monitoring tools need recent versions to show virtual threads correctly.
2. Inspect what the code does
Look for the four things that work against virtual threads:
| Look for | Why | How to find it |
|---|---|---|
| Long native calls, or slow work in static initializers | they pin on every version (article 14) | jdk.VirtualThreadPinned events in JFR (article 16) |
Blocking inside synchronized (only on Java 21–23) | it pins | the same JFR events |
| Thread-local caches of large objects | one copy per virtual thread (article 15) | -Djdk.traceVirtualThreadLocals, heap dumps |
| Long CPU-bound tasks | no time slicing: they hog carriers | profiling, knowledge of the workload |
Run the application's tests and a representative load on virtual threads with JFR enabled, then fix the top pinning stacks before production. Not every finding needs a fix: pinning that is rare and short doesn't matter.
3. Switch to virtual threads
In plain Java, replace the pool that runs blocking, per-request work with a virtual thread per task:
// Before
ExecutorService requests = Executors.newFixedThreadPool(200);
// After
ExecutorService requests = Executors.newVirtualThreadPerTaskExecutor();
Leave other pools as they are. A pool for CPU-bound work should stay sized to the cores, and a ScheduledExecutorService for timers doesn't need to change.
Frameworks usually expose a single setting. Part 7 covers them in detail:
- Spring Boot 3.2+:
spring.threads.virtual.enabled=trueruns web requests,@Asyncmethods and several other executors on virtual threads. - Quarkus: annotate endpoints with
@RunOnVirtualThread. - Helidon 4: its web server runs every request on a virtual thread by default.
- Tomcat and Jetty: configure the connector or thread pool to use virtual threads (for example, Tomcat's
useVirtualThreadsconnector attribute).
4. Replace accidental limits with explicit ones
This is the step most often forgotten. A pool of 200 threads quietly limited every downstream system to 200 concurrent calls. With virtual threads that limit is gone (article 12). For each scarce resource, decide on an explicit limit:
- Databases: the connection pool's maximum size, with a sensible connection timeout.
- Rate-limited or fragile remote services: a semaphore (bulkhead) or rate limiter, and a timeout on every call.
- Memory-heavy work: a semaphore on how many large requests run at once, so a spike can't exhaust the heap.
- Incoming load: a limit at the edge (the server's maximum connections, a load balancer or an API gateway) so the service sheds excess load with clear errors.
The program below shows the difference with the course's trip-quote service. Each request loads the traveler from a database that allows 20 connections, then finds a flight and a hotel. Each call takes 50 ms. It runs 400 requests three ways: on the old pool, after a naive switch, and after a proper migration:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
record Traveler(String id, String homeCity) {}
record Flight(String route, int price) {}
record Hotel(String name, int price) {}
record Quote(int total) {}
static void waitFor(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
/** The database allows 20 connections; it counts the most it ever sees at once. */
static final AtomicInteger dbActive = new AtomicInteger(), dbPeak = new AtomicInteger();
static Traveler loadTraveler(String id) {
int now = dbActive.incrementAndGet();
dbPeak.accumulateAndGet(now, Math::max);
try { waitFor(50); return new Traveler(id, "Oslo"); } finally { dbActive.decrementAndGet(); }
}
static Flight findFlight(Traveler t) { waitFor(50); return new Flight(t.homeCity() + "-Lisbon", 240); }
static Hotel findHotel() { waitFor(50); return new Hotel("Casa Azul", 360); }
static Quote price(Flight f, Hotel h) { return new Quote(f.price() + h.price()); }
// The same request-handling code serves both versions
static Quote handle(String travelerId, Semaphore dbPermits) throws InterruptedException {
Traveler traveler;
if (dbPermits == null) {
traveler = loadTraveler(travelerId);
} else {
dbPermits.acquire(); // explicit limit for the scarce resource
try { traveler = loadTraveler(travelerId); } finally { dbPermits.release(); }
}
return price(findFlight(traveler), findHotel());
}
static void serve(String label, ExecutorService executor, Semaphore dbPermits, int requests) {
dbPeak.set(0);
AtomicInteger ok = new AtomicInteger();
long start = System.nanoTime();
try (executor) {
for (int i = 0; i < requests; i++) {
String id = "t-" + i;
executor.submit(() -> { if (handle(id, dbPermits).total() == 600) ok.incrementAndGet(); return null; });
}
}
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.printf("%-38s %d quotes in about %4d ms, peak DB connections %d%n",
label, ok.get(), Math.round(ms / 50.0) * 50, dbPeak.get());
}
public static void main(String[] args) {
int requests = 400;
// Before: the pool size limits everything, including the database (by accident)
serve("before: fixed pool of 20 threads", Executors.newFixedThreadPool(20), null, requests);
// Naive migration: no pool, so no limit at all on the database
serve("naive: virtual threads, no limit", Executors.newVirtualThreadPerTaskExecutor(), null, requests);
// Proper migration: virtual threads plus an explicit limit where it's needed
serve("after: virtual threads + Semaphore(20)", Executors.newVirtualThreadPerTaskExecutor(),
new Semaphore(20), requests);
}
}
A typical run (times may differ slightly from machine to machine):
before: fixed pool of 20 threads 400 quotes in about 3250 ms, peak DB connections 20
naive: virtual threads, no limit 400 quotes in about 150 ms, peak DB connections 400
after: virtual threads + Semaphore(20) 400 quotes in about 1200 ms, peak DB connections 20
- Before: 20 threads each spend 150 ms per request, so 400 requests take 20 rounds, about 3 seconds. The database never sees more than 20 connections, but only because nothing else could run either.
- Naive: very fast, because all 400 requests run at once, but the database saw 400 concurrent connections, twenty times its limit. A real database would refuse connections or slow to a crawl.
- After: the database stage is limited to 20 at a time (about 1 second for 400 lookups), while the flight and hotel calls, which have no such limit, run concurrently. The result is almost three times faster than before, and the database is protected.
The lesson generalizes: virtual threads move the bottleneck to the real scarce resource, so that resource needs an explicit limit.
5. Test under load and compare
Measure the old and new versions under the same realistic load, with JFR running:
- Latency percentiles (p50, p99) and throughput: the reason for migrating. Expect gains only under concurrency and only for I/O-bound work (article 10).
- CPU use: should stay similar for the same throughput. A large increase may point to busy-waiting code or to more work being let through.
- Heap and GC: stacks now live on the heap. More concurrent requests means more live objects, so the heap may need adjusting.
- Pinning and submit-failed events: should be rare.
- Downstream systems: watch their load too, to confirm the limits from step 4 work.
6. Roll out gradually
- Put the switch behind configuration, so a rollback is a restart, not a redeploy.
- Start with one service, or one instance behind the load balancer, and compare its metrics with the others.
- Keep thread dumps readable by naming virtual threads that do distinct jobs (article 17).
- Expand once the numbers hold under real traffic.
Common pitfalls
- Pooling virtual threads, for example
Executors.newFixedThreadPool(200, Thread.ofVirtual().factory()). It brings back queuing and hides the intent. Create one per task and limit resources instead. - Expecting faster requests. Each request takes as long as before. Throughput under load is what improves.
- Moving CPU-bound work onto virtual threads. It gains nothing and can starve request threads.
- Forgetting timeouts. With unlimited cheap threads, a hung dependency can collect a very large number of waiting requests. Every remote call needs a timeout.
- Assuming
synchronizedis fine on Java 21. It's fine on Java 24+. On 21–23, check JFR for pinning.
What's current
- Java 25 LTS is the recommended baseline: virtual threads with JEP 491's pinning fix, final scoped values, and mature tooling.
- Major frameworks support virtual threads with a single setting, and several, such as Helidon 4, use them by default.
- Structured concurrency, the next step in the virtual-thread model, is final in Java 28 (expected March 2027) after previews in Java 21–27. Part 4 covers it.
Common questions
How much code changes in a typical migration? Often a line or two: the executor or a framework property. Most of the work is upgrading dependencies, adding limits and testing.
Can I run virtual and platform threads side by side? Yes, and most applications do: virtual threads for request handling, platform pools for CPU-bound work and for the rare long native calls.
What if a key library pins heavily and has no update? Isolate it: call it through a bounded platform-thread pool and wait on the result from the virtual thread (article 14). A semaphore around the library also caps how many carriers it can hold, but set the limit well below the number of carriers.
Should a new project start with virtual threads? For I/O-bound services on Java 21+, yes, preferably on Java 25. Write simple blocking code, one thread per task, with explicit limits on downstream resources.
Summary
- Upgrade to Java 24+ (ideally 25 LTS) and current libraries before switching.
- Inspect for long native calls, thread-local caches, CPU-heavy work and, on older JDKs,
synchronizedblocking, using JFR and thread-local tracing. - Switch blocking per-request work to a virtual thread per task, often with one setting. Leave CPU pools alone.
- Replace the old pool's accidental limits with explicit ones: connection pools, semaphores, rate limiters and timeouts.
- Load test with JFR, compare latency, throughput, CPU, memory and downstream load, then roll out gradually.
Practice questions
After switching a service to virtual threads, throughput doubled in testing, but in production the database started rejecting connections during peaks. What was missed, and how do you fix it?
Answer
The old request pool had been limiting concurrent database access by accident. Without it, peaks send far more concurrent queries than the database allows. Cap the database explicitly: size the connection pool to what the database can handle and set a connection timeout, so excess requests wait briefly or fail fast instead of overwhelming it.
Which of these pools should usually be switched to virtual threads? (a) the web server's request pool, (b) a ForkJoinPool for image resizing, (c) a pool that runs 50 parallel HTTP calls per batch job, (d) a single-threaded scheduled executor that runs a cleanup every minute.
Answer
(a) and (c). Both run blocking I/O tasks. (b) is CPU-bound, so keep it sized to the cores. (d) gains nothing: it's one thread that wakes up once a minute.
A team wants to keep their limit of 200 concurrent requests and writes Executors.newFixedThreadPool(200, Thread.ofVirtual().factory()). What would you suggest instead, and why?
Answer
Use newVirtualThreadPerTaskExecutor() and put the limit where it's needed: a semaphore or connection pool in front of each scarce resource, plus a connection limit at the server edge. A pool of virtual threads queues tasks invisibly, limits work that doesn't need limiting, and hides what is actually being protected.
Review quiz
Test yourself on Part 2 with the Part 2 review quiz: Java Virtual Threads in Depth. Twenty questions cover virtual-thread properties and creation, Little's Law, mounting and unmounting, semaphores and rate limits, pinning before and after Java 24, native calls and other limitations, thread-locals, JFR, thread dumps and migration.
Previous: Java Virtual Thread Dumps With jcmd: JSON Format, Thread Containers and HotSpotDiagnosticMXBean
Next: Building a Thread Pool From Scratch in Java: Worker Threads and a Task Queue

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.