Sub topic 8
Choosing Virtual Threads: I/O-Bound vs CPU-Bound Work
Virtual threads are a strong tool, but they do not fit every job. This chapter shows you how to tell whether they will help your program. You will run two small experiments. In one, virtual threads make the program much faster. In the other, they change almost nothing. By the end, you will be able to look at a task and predict which group it belongs to.
Two kinds of work
Every task a thread runs spends its time in one of two ways.
- I/O-bound work spends most of its time waiting. I/O means input/output: reading a file, calling a web service, or querying a database. While the thread waits for the answer, the CPU has nothing to do for it.
- CPU-bound work spends most of its time computing. Examples are resizing an image, compressing data, or searching for prime numbers. The CPU stays busy the whole time.
A CPU core is one part of the processor that can run one thread's instructions at a time. A laptop might have 8 cores. Only 8 threads can truly run at the same moment on that laptop, no matter how many threads exist.
This number explains the whole chapter. Virtual threads make waiting cheap. They do not add CPU cores. So they help when your tasks wait a lot, and they barely help when your tasks compute a lot.
Throughput, not speed
Beginners often think virtual threads make code run faster. They do not. One virtual thread runs your code at the same speed as one platform thread.
What virtual threads improve is throughput. Throughput is how many tasks your program finishes per second. If each task waits 200 milliseconds for a database, a single task still takes 200 milliseconds. But with virtual threads, you can have thousands of tasks waiting at once instead of a few dozen. More tasks finish each second.
Experiment 1: I/O-bound tasks
This program runs 1,000 tasks. Each task sleeps for 200 milliseconds to stand in for a slow network call. First it uses a fixed pool of 20 platform threads. Then it uses one virtual thread per task.
import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class IoBoundDemo {
static void runTasks(String label, ExecutorService executor, int tasks) {
long start = System.nanoTime();
try (executor) {
for (int i = 0; i < tasks; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(200)); // stands in for a network call
return null;
});
}
} // close() waits for every task to finish
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(label + ": " + millis + " ms");
}
public static void main(String[] args) {
int tasks = 1_000;
runTasks("Fixed pool of 20 platform threads", Executors.newFixedThreadPool(20), tasks);
runTasks("Virtual thread per task", Executors.newVirtualThreadPerTaskExecutor(), tasks);
}
}On a typical machine the output looks like this:
Fixed pool of 20 platform threads: 10052 ms
Virtual thread per task: 231 msHere is why. The pool has only 20 threads, so only 20 tasks can wait at the same time. The 1,000 tasks go through in 50 rounds of 200 milliseconds each, which is about 10 seconds. With virtual threads, all 1,000 tasks wait at the same time. While a virtual thread sleeps, it lets go of its carrier thread, so the waiting costs almost nothing. Everything finishes in about one round.
That is a speedup of more than 40 times, and no task's code changed.
Experiment 2: CPU-bound tasks
Now the tasks do real computing. Each task counts the prime numbers in a block of 100,000 numbers. A prime number is a whole number greater than 1 that can only be divided evenly by 1 and itself.
This program compares a pool sized to the number of CPU cores with one virtual thread per task.
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 CpuBoundDemo {
static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) {
return false;
}
}
return true;
}
static long countPrimes(int from, int to) {
long count = 0;
for (int n = from; n < to; n++) {
if (isPrime(n)) {
count++;
}
}
return count;
}
static void run(String label, ExecutorService executor) throws Exception {
long start = System.nanoTime();
long total = 0;
try (executor) {
List<Future<Long>> results = new ArrayList<>();
int chunk = 100_000;
for (int i = 0; i < 50; i++) {
int from = i * chunk;
int to = from + chunk;
results.add(executor.submit(() -> countPrimes(from, to)));
}
for (Future<Long> result : results) {
total += result.get();
}
}
long millis = (System.nanoTime() - start) / 1_000_000;
System.out.println(label + ": " + total + " primes in " + millis + " ms");
}
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("CPU cores: " + cores);
run("Fixed pool of " + cores + " platform threads", Executors.newFixedThreadPool(cores));
run("Virtual thread per task", Executors.newVirtualThreadPerTaskExecutor());
}
}Sample output on an 8-core machine:
CPU cores: 8
Fixed pool of 8 platform threads: 348513 primes in 412 ms
Virtual thread per task: 348513 primes in 398 msBoth versions take about the same time. Your numbers will differ, and the first run can be a little slower while the JVM warms up. The answer is always 348,513 primes below 5,000,000.
The tasks never wait. They keep the CPU busy the whole time. By default the virtual thread scheduler uses about one carrier thread per core, so at most 8 virtual threads run at once, the same as the 8-thread pool. Making waiting cheap does nothing when no task waits.
Why I/O helps and CPU does not
This diagram follows the decision a JVM effectively makes for each task.
A warning about long CPU work on virtual threads
Platform threads take turns on the CPU. The operating system interrupts a busy thread every so often so that others can run. This is called time-slicing.
The virtual thread scheduler does not time-slice. A virtual thread gives up its carrier only when it blocks, for example on sleep, I/O, or a lock. A virtual thread that computes for 10 seconds without blocking holds its carrier for all 10 seconds.
Mixed work: the common real case
Real tasks usually mix both kinds of work. A web request handler might do this:
- Read a user record from a database (wait 30 ms).
- Call a pricing service (wait 50 ms).
- Build a JSON response (compute 1 ms).
This task spends 80 of its 81 milliseconds waiting. It is I/O-bound overall, and virtual threads suit it well. The question to ask is always "what fraction of the time does this task wait?" If most of its time is waiting, virtual threads will help.
Other cases where virtual threads do not help
Virtual threads also give little or no benefit in these cases.
| Situation | Why virtual threads do not help much |
|---|---|
| Few concurrent tasks, such as 10 at a time | A small platform pool already handles 10 waiting tasks well |
| Purely CPU-bound work | The number of cores is the limit, not the number of threads |
| The downstream system is the limit | A database that accepts 10 connections still serves only 10 queries at once |
| Long calls into native code | The virtual thread cannot unmount during native calls, so it holds its carrier |
The third row matters a lot in practice. Virtual threads let you send 10,000 requests at once, but the database on the other end may not be able to handle them. The next chapter shows how to protect such a resource with a semaphore.
A quick checklist
Use virtual threads when all of these are true:
- Your program handles many tasks at the same time (hundreds or more).
- Each task spends most of its time waiting on I/O.
- The task code uses normal blocking calls, such as JDBC, HTTP clients, or file reads.
Keep a platform thread pool, sized close to your core count, when tasks mostly compute.
Measuring instead of guessing
If you are not sure which group a task belongs to, measure it. Wrap the task with timers. Compare wall-clock time (the real time from start to finish) with CPU time (the time the CPU actually spent on the thread). Java can report CPU time for platform threads through ThreadMXBean. If wall-clock time is much larger than CPU time, the task is mostly waiting, and virtual threads are a good fit.
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class MeasureTask {
public static void main(String[] args) throws InterruptedException {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long wallStart = System.nanoTime();
long cpuStart = bean.getCurrentThreadCpuTime();
Thread.sleep(300); // waiting part
long sum = 0;
for (int i = 0; i < 50_000_000; i++) { // computing part
sum += i;
}
long wallMs = (System.nanoTime() - wallStart) / 1_000_000;
long cpuMs = (bean.getCurrentThreadCpuTime() - cpuStart) / 1_000_000;
System.out.println("sum = " + sum);
System.out.println("Wall time: " + wallMs + " ms, CPU time: " + cpuMs + " ms");
}
}The main thread is a platform thread, so the CPU time reading works here. If the output shows about 330 ms of wall time and 30 ms of CPU time, the task spends about 90% of its time waiting.
Exercise
A service handles 5,000 requests at the same time. Each request waits 400 ms for a remote API and then spends 2 ms formatting the result. It currently uses a fixed pool of 100 platform threads. Will switching to virtual threads raise throughput? Explain why.
Show answer
Yes. Each request spends about 400 of its 402 ms waiting, so the work is I/O-bound. With 100 pool threads, only 100 requests can wait at once, and the rest queue. With virtual threads, all 5,000 can wait at the same time because a waiting virtual thread releases its carrier. One request still takes about 402 ms, but far more requests finish per second, as long as the remote API can handle the extra load.
Exercise
A program converts 200 large videos. Each conversion keeps one CPU core at 100% for two minutes and reads its input file in under a second. The machine has 16 cores. Should you use virtual threads?
Show answer
No. The work is CPU-bound, so at most 16 conversions can make progress at once, whatever the thread type. Virtual threads add no throughput. They also do not time-slice, so long conversions would hold every carrier thread. A fixed platform pool of about 16 threads is the better choice.
Exercise
In IoBoundDemo, change the fixed pool size from 20 to 1,000 and run it again. What happens to the time, and why might this still be a poor choice in a real server?
Show answer
The time drops to roughly 200–300 ms, close to the virtual thread version, because 1,000 platform threads can all wait at once. In a real server, though, each platform thread reserves its own large stack and an operating-system thread. At 10,000 or 100,000 concurrent requests, that memory and OS cost becomes a problem. Virtual threads reach the same throughput at a small fraction of that cost.