Sub topic 13
Migrating Existing Thread-Pool Code
Many Java programs already use thread pools. A thread pool is a fixed group of platform threads that take turns running your tasks. Pools were the standard way to limit how many expensive threads a program made. With virtual threads, that limit is often no longer needed.
This chapter shows how to move existing pool-based code to virtual threads one safe step at a time. It brings together ideas from earlier chapters: the virtual-thread-per-task executor, semaphores, thread locals, and pinning. The goal is a migration that keeps working code working.
What "Migrating" Means Here
Migrating means changing code so it runs on a new technology without changing what it does. Here, the work your tasks do stays the same. Only the thread type that runs them changes.
Most migrations need three kinds of change:
- Swap the executor that creates threads.
- Replace any limit that the pool size used to provide.
- Check for patterns that behave badly with many threads, such as thread-local caches and pinning.
Step 1: Pick the Right Pools
Not every pool should move. Virtual threads help when tasks spend most of their time waiting: on the network, a database, files, or sleeps. They do not make CPU-bound work faster. CPU-bound work is work that keeps the processor busy, such as math or image resizing.
| Pool type in your code | Typical work | Migrate? |
|---|---|---|
| `newFixedThreadPool(200)` for HTTP calls | Waiting on remote servers | Yes |
| `newCachedThreadPool()` for database queries | Waiting on the database | Yes |
| `newFixedThreadPool(cores)` for number crunching | CPU-bound | No |
| `ForkJoinPool` or parallel streams | Splitting CPU work | No |
| `newScheduledThreadPool(1)` for timers | Running tasks on a schedule | Usually no |
Step 2: Swap the Executor
Here is a typical program before migration. It runs 200 blocking calls on a pool of 20 platform threads. Thread.sleep(200) stands in for a slow network call.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class BeforeMigration {
static String fetch(int id) throws InterruptedException {
Thread.sleep(200); // stands in for a network call
return "result " + id;
}
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
ExecutorService pool = Executors.newFixedThreadPool(20);
try {
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 200; i++) {
int id = i;
futures.add(pool.submit(() -> fetch(id)));
}
for (Future<String> f : futures) {
f.get();
}
} finally {
pool.shutdown();
}
System.out.println("Took " + (System.currentTimeMillis() - start) + " ms");
}
}Only 20 tasks run at once, so the 200 tasks finish in about 10 rounds. That takes roughly 2,000 ms.
Now the migrated version. The task code does not change. The executor line changes, and try-with-resources replaces the manual shutdown().
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class AfterMigration {
static String fetch(int id) throws InterruptedException {
Thread.sleep(200); // stands in for a network call
return "result " + id;
}
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 200; i++) {
int id = i;
futures.add(executor.submit(() -> fetch(id)));
}
for (Future<String> f : futures) {
f.get();
}
} // close() waits for all tasks
System.out.println("Took " + (System.currentTimeMillis() - start) + " ms");
}
}Every task gets its own virtual thread, and all 200 wait at the same time. The program finishes in about 200 ms plus a little startup time.
Because both versions use the ExecutorService interface, the rest of your code (submit, Future, get) stays the same. An interface is a Java type that lists methods without fixing how they work. That shared interface is what makes this swap small.
Step 3: Replace the Limit the Pool Used to Give You
A fixed pool of 20 threads did two jobs. It saved memory, and it also made sure no more than 20 tasks hit the database or remote service at once. The new executor has no such cap. If that downstream system can only handle 20 connections, it may now get 200 at once and start failing.
Ask this question for every pool you migrate: was the pool size protecting something? If yes, add a Semaphore around the scarce resource, as the earlier chapter on limiting concurrency showed. A semaphore is a counter of permits. A thread must take a permit before it continues, and it gives the permit back when done.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class MigratedWithLimit {
private static final Semaphore DB_PERMITS = new Semaphore(20); // same limit as the old pool
static String query(int id) throws InterruptedException {
DB_PERMITS.acquire();
try {
Thread.sleep(100); // stands in for a database call
return "row " + id;
} finally {
DB_PERMITS.release();
}
}
public static void main(String[] args) {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 500; i++) {
int id = i;
executor.submit(() -> query(id));
}
}
System.out.println("All queries done");
}
}Put the semaphore around the protected resource only. Code that does not touch the database still runs freely.
Step 4: Check Thread Locals
A thread local (ThreadLocal) stores a separate value for each thread. In pool-based code, people often used one as a cache. Each of the 20 pool threads kept one expensive object and reused it for every task.
With virtual threads, each task gets a new thread. A cache like that now creates a new object for every task and throws it away at the end. With a million tasks, that is a million objects.
Here is a common old pattern and its fix. SimpleDateFormat is not safe to share between threads, so code stored one per thread. The modern DateTimeFormatter is safe to share, so one constant is enough.
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class ThreadLocalFix {
// Old: one formatter per thread. With virtual threads, one per task.
private static final ThreadLocal<SimpleDateFormat> OLD_FORMAT =
ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));
// New: one shared, thread-safe formatter for everyone.
private static final DateTimeFormatter NEW_FORMAT =
DateTimeFormatter.ofPattern("yyyy-MM-dd");
public static void main(String[] args) {
System.out.println(OLD_FORMAT.get().format(new Date()));
System.out.println(NEW_FORMAT.format(LocalDate.now()));
}
}Thread locals that carry per-request data, such as a user ID, still work with virtual threads. The thread locals to look for are the ones used as caches of expensive objects.
Step 5: Check for Pinning
Pinning happens when a virtual thread cannot let go of its carrier thread while it blocks. The carrier is the platform thread the virtual thread runs on. On JDK 21 to 23, blocking inside a synchronized block or method causes pinning. JDK 24 removed that case (JEP 491). Calls into native code can still pin on any version.
What to do depends on your JDK:
- JDK 24 or later:
synchronizedis fine. You usually need no changes. - JDK 21 to 23: look for
synchronizedcode that does slow I/O inside it. Replace it withReentrantLockwhere blocking is long or frequent. Shortsynchronizedblocks that only touch memory are fine to leave.
To find pinning, record a JDK Flight Recorder session and look for jdk.VirtualThreadPinned events, as the observability chapter described:
java -XX:StartFlightRecording=duration=60s,filename=app.jfr -jar app.jar
jfr print --events jdk.VirtualThreadPinned app.jfrStep 6: Measure Before and After
A migration is done only when numbers show it helped. Run the same load test on the old and new versions, and compare:
- Throughput: requests or tasks finished per second.
- Latency: how long each request takes, especially the slowest ones.
- Errors: timeouts or "too many connections" from downstream systems.
- Memory: heap use, which grows if thread-local caches multiply.
If throughput does not rise, your tasks may be CPU-bound, or a downstream limit may be the real bottleneck.
The Whole Process
Common Mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Pooling virtual threads, for example `newFixedThreadPool(20, Thread.ofVirtual().factory())` | You keep the old cap and gain little | Use one virtual thread per task |
| Removing the pool with no replacement limit | The database or API gets overloaded | Add a `Semaphore` |
| Migrating CPU-heavy pools | No speedup, more overhead | Keep a pool sized to the core count |
| Keeping thread-local caches | Memory use climbs | Share thread-safe objects instead |
| Migrating everything at once | Hard to tell which change caused a problem | Move one pool at a time and measure |
Exercise
An application uses Executors.newFixedThreadPool(50) to call a payment API that allows at most 50 open connections. You switch to Executors.newVirtualThreadPerTaskExecutor(), and the API starts returning "too many connections" errors. What happened, and how do you fix it?
Show answer
The fixed pool of 50 threads was also limiting the connections to the payment API to 50. The virtual-thread executor has no cap, so many more calls now run at once. Fix it by wrapping the API call in a Semaphore with 50 permits: acquire before the call and release in a finally block.
Exercise
A team has a pool sized to the number of CPU cores that resizes images, and another pool of 100 threads that reads files from network storage. Which pool should they migrate to virtual threads, and why?
Show answer
Migrate the file-reading pool. Its tasks spend most of their time waiting on I/O, so many virtual threads can wait at once cheaply. The image-resizing pool is CPU-bound. More threads cannot beat the number of cores, so it should stay a platform-thread pool sized to the core count.
Exercise
After migrating, memory use rises sharply. The code has a ThreadLocal that holds a large buffer created with ThreadLocal.withInitial(). Why did this get worse after migration?
Show answer
With a pool, only a few long-lived threads existed, so only a few buffers were created and reused. With virtual threads, each task runs on a new thread, so each task creates its own buffer. Fix it by sharing a thread-safe object, passing the buffer as a parameter, or allocating a small buffer only when needed.