Sub topic 2
Why Thread-per-Request Runs Out of Threads
The last chapter showed that each Java platform thread is costly. This chapter shows why that cost matters so much for servers, and why servers hit a limit long before the computer is actually busy.
What thread-per-request means
A server is a program that answers requests from other programs. A request is one message asking for work, such as "show me my order history."
Thread-per-request is a simple way to build a server. Each new request gets its own thread. That thread handles the request from start to finish, then moves on to the next one.
People like this model because the code is easy to read. You write plain steps, one after another:
- Read the request.
- Ask the database for data.
- Call another service.
- Send back the answer.
Each step runs in order on the same thread. You do not need callbacks or other tricks.
Most of the time, threads just wait
Steps 2 and 3 talk to other computers over the network. While a thread waits for the answer, it is blocked. A blocked thread is stopped and can do nothing else until the answer arrives.
A typical request might look like this:
| Step | Time | Thread is... |
|---|---|---|
| Parse request | 1 ms | working |
| Database query | 50 ms | waiting |
| Call other service | 40 ms | waiting |
| Build response | 1 ms | working |
The thread works for 2 ms and waits for 90 ms. It spends almost all of its time waiting. The CPU sits idle, but the thread still holds its memory and its spot in the pool.
The thread pool sets a hard limit
Platform threads are expensive, so servers do not create unlimited numbers of them. They use a thread pool, which is a fixed group of threads that are reused for many tasks. A common pool size is about 200 threads.
Suppose all 200 threads are waiting on the database. A new request arrives. No thread is free, so the request goes into a queue and waits its turn. The server is "full" even though the CPU is barely working.
Throughput is how many requests a server finishes per second. With thread-per-request, throughput is capped by the number of threads:
- 200 threads, each request takes about 0.1 seconds.
- Each thread finishes about 10 requests per second.
- Total: about 200 × 10 = 2,000 requests per second, at most.
To go higher, you need more threads. But each platform thread costs memory and operating system resources, so you cannot simply ask for 100,000 of them.
See the limit yourself
This program uses a pool of 10 platform threads to run 50 tasks. Each task sleeps for 1 second to stand in for a slow database call.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class PoolLimit {
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
ExecutorService pool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 50; i++) {
pool.submit(() -> {
try {
Thread.sleep(1000); // pretend to wait for a database
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.MINUTES);
long seconds = (System.currentTimeMillis() - start) / 1000;
System.out.println("Finished in about " + seconds + " seconds");
}
}The program prints about 5 seconds. Only 10 tasks can wait at once, so the 50 tasks run in 5 rounds. The CPU did almost nothing that whole time.
The core problem
The problem is the number of threads. Thread-per-request needs one thread for every request in progress, and platform threads are too costly to have in the many thousands. Waiting is cheap for the CPU but expensive for the thread pool.
Exercise
A server has a pool of 100 platform threads. Each request spends 200 ms in total, mostly waiting on a database. About how many requests per second can it handle at most?
Show answer
Each thread finishes 1 / 0.2 = 5 requests per second. With 100 threads, that is about 100 × 5 = 500 requests per second.
Exercise
In the PoolLimit program, what would happen to the total time if you changed the pool size from 10 to 50?
Show answer
All 50 tasks could sleep at the same time, so the program would finish in about 1 second instead of about 5.