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. If those tasks spend most of their time waiting on network calls, files, or databases, you can often move them to virtual threads with a small change. This chapter walks through that change step by step.
Step 1: Find Pools That Run Blocking Work
Search your code for places that create pools, such as Executors.newFixedThreadPool(...) or Executors.newCachedThreadPool(). Then look at what each pool runs.
- If the tasks mostly wait on I/O (input and output, like HTTP calls or database queries), they are good candidates.
- If the tasks mostly do heavy calculation, leave the pool alone. Virtual threads do not make the CPU faster.
Step 2: Swap the Executor
Here is a typical program before migration. A fixed pool of 50 threads runs 500 tasks that each wait 200 milliseconds.
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(50);
try {
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 500; 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 50 tasks can wait at once, so this takes about 2,000 ms. Now replace the pool with a virtual-thread-per-task executor:
import java.util.ArrayList;
import java.util.List;
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 (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 500; i++) {
int id = i;
futures.add(executor.submit(() -> fetch(id)));
}
for (Future<String> f : futures) {
f.get();
}
}
System.out.println("Took " + (System.currentTimeMillis() - start) + " ms");
}
}Every task gets its own virtual thread, so all 500 wait together. The program finishes in about 200 ms. The task code did not change at all.
Step 3: Check What the Old Pool Size Was Protecting
Sometimes a pool size was a hidden limit. For example, the old pool of 50 might have kept you from opening more than 50 database connections. When you remove the pool, you also remove that limit. If a resource is scarce, add a Semaphore around it, as shown in the earlier chapter on limiting concurrency.
Step 4: Review Thread Locals and Locks
Two more things need a look before you ship:
| Check | What to look for | What to do |
|---|---|---|
| Thread locals | A `ThreadLocal` used as a cache of expensive objects | Share one object safely or create it per task, since each virtual thread gets its own copy |
| Pinning | Long blocking calls inside `synchronized` on JDK 21 to 23 | Switch to `ReentrantLock`, or upgrade to JDK 24 or later |
Step 5: Test and Observe
Run your tests, then watch the program under load. Use thread dumps and JDK Flight Recorder events, covered in the previous chapter, to spot pinned threads or a resource that has become a bottleneck.
Exercise
Your service uses Executors.newFixedThreadPool(20) to run tasks that call a payment API. The API allows at most 20 calls at a time. What should you change when you migrate to virtual threads?
Show answer
Replace the fixed pool with Executors.newVirtualThreadPerTaskExecutor(), and wrap each payment API call with a Semaphore that has 20 permits. Removing the pool also removes the old limit of 20, so the semaphore keeps the API safe while each task still gets its own virtual thread.
Exercise
A pool runs tasks that resize large images entirely in memory. Should you migrate it to virtual threads?
Show answer
No. Resizing images is CPU-bound work. Virtual threads help when tasks spend time waiting, so a pool sized to the number of CPU cores remains the better choice.