Sub topic 8
Choosing Virtual Threads: I/O-Bound vs CPU-Bound Work
Virtual threads make waiting cheap. They do not make your computer compute faster. This chapter shows how to tell which kind of work you have, so you know whether virtual threads will help.
Two Kinds of Work
Most tasks spend their time in one of two ways.
- I/O-bound work is work that spends most of its time waiting. I/O means input/output, such as reading a file, calling a web service, or querying a database. While the task waits for an answer, the CPU has nothing to do for it.
- CPU-bound work is work that keeps the processor busy the whole time. Examples are resizing images, compressing files, or doing heavy math.
| Task | Kind | Where the time goes |
|---|---|---|
| Calling a REST API | I/O-bound | Waiting for the network |
| Reading rows from a database | I/O-bound | Waiting for the database |
| Counting prime numbers | CPU-bound | Doing arithmetic |
| Encoding a video | CPU-bound | Doing arithmetic |
Why Virtual Threads Help I/O-Bound Work
A virtual thread that blocks (stops to wait) gives its carrier thread back. The carrier then runs another virtual thread. So 10,000 waiting tasks need only a few real operating system threads.
The gain is throughput, meaning how many tasks finish per second. A single request does not run faster. The server simply handles many more requests at the same time, because waiting no longer uses up a scarce thread.
Why Virtual Threads Do Not Help CPU-Bound Work
A CPU-bound task never waits, so it never gives up its carrier. Your machine can only run as many tasks at once as it has CPU cores. If you have 8 cores, only 8 calculations can run at one moment, whether you start 8 threads or 8 million.
The program below runs the same CPU-heavy job twice: once on a fixed pool sized to your cores, and once on virtual threads.
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 CpuBound {
static long countPrimes(int limit) {
long count = 0;
for (int n = 2; n < limit; n++) {
boolean prime = true;
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) {
prime = false;
break;
}
}
if (prime) count++;
}
return count;
}
static long run(ExecutorService executor) throws Exception {
long start = System.nanoTime();
try (executor) {
List<Future<Long>> results = new ArrayList<>();
for (int i = 0; i < 100; i++) {
results.add(executor.submit(() -> countPrimes(200_000)));
}
for (Future<Long> f : results) {
f.get();
}
}
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) throws Exception {
int cores = Runtime.getRuntime().availableProcessors();
System.out.println("Fixed pool of " + cores + ": "
+ run(Executors.newFixedThreadPool(cores)) + " ms");
System.out.println("Virtual threads: "
+ run(Executors.newVirtualThreadPerTaskExecutor()) + " ms");
}
}When you run it, the two times come out about the same. Both versions are limited by the number of cores. Virtual threads added no speed because no task ever waited.
A Simple Decision Guide
Ask these questions about your workload:
- Does each task spend most of its time waiting? If yes, virtual threads are a good fit.
- Do you have hundreds or thousands of tasks running at once? Then the gain is largest.
- Is the work mostly calculation? Then virtual threads will not raise throughput.
Exercise
A program fetches 5,000 web pages, and each fetch waits about 1 second for the network. Another program applies a blur filter to 5,000 large images on an 8-core machine. Which program benefits from virtual threads, and why?
Show answer
The web page fetcher benefits. Its tasks spend almost all their time waiting, so each blocked virtual thread frees its carrier and thousands of fetches can wait at the same time. The image program is CPU-bound: only 8 blurs can run at once on 8 cores, so virtual threads add no throughput.
Exercise
Do virtual threads make a single database request return faster?
Show answer
No. One request still waits just as long for the database. Virtual threads raise throughput, the number of requests handled at once, and do not change the time of one request.