Sub topic 2
Why Thread-per-Request Runs Out of Threads
The previous chapter showed that every Java thread you have used so far is a platform thread, and each one costs real memory and operating system resources. This chapter shows what happens when a server puts those threads to work in the most common design: one thread for each request. That design is simple to write, but it stops scaling long before the computer runs out of CPU power. Knowing why it stops is the main reason virtual threads exist.
The Thread-per-Request Model
A request is one unit of work a server receives, such as "show me order 42" from a web browser. The thread-per-request model is a design where the server gives each incoming request its own thread. That thread handles the request from start to finish and then becomes free for the next one.
This model is popular because the code reads like a recipe. You write steps one after another:
- Read the request.
- Ask the database for the order.
- Ask a payment service for the payment status.
- Build the response and send it back.
Each step runs on the same thread, in order. If step 2 fails, the stack trace shows exactly where. Debuggers can step through it line by line. Most Java web frameworks, such as classic Servlet containers, have worked this way for decades.
Waiting Is Most of the Work
Look at the recipe again. Steps 2 and 3 talk to other machines over the network. While the thread waits for the database to answer, it does nothing. It is blocked, which means it is paused until some outside event happens, like data arriving.
In a typical business application, a request might spend 2 milliseconds using the CPU and 200 milliseconds waiting for the database and other services. The thread is busy for about 1% of that time. For the other 99%, it sits idle while still holding its memory and its slot in the operating system.
How Many Threads Do You Need? Little's Law
You can work out how many threads a server needs with a simple rule called Little's Law. It says:
- concurrency = throughput × time per request
Here concurrency is how many requests are in progress at the same moment. Throughput is how many requests finish per second. Time per request is how long each one takes, in seconds, including all the waiting.
In thread-per-request, each request in progress needs one thread. So concurrency tells you how many threads you need.
| Throughput (requests/second) | Time per request | Threads needed |
|---|---|---|
| 100 | 0.2 s | 20 |
| 1,000 | 0.2 s | 200 |
| 5,000 | 0.2 s | 1,000 |
| 5,000 | 1.0 s | 5,000 |
| 20,000 | 1.0 s | 20,000 |
The last rows are the problem. If a slow service makes each request take one second, a server handling 20,000 requests per second needs 20,000 threads at once. Platform threads usually reserve about 1 MB of stack memory each by default on 64-bit systems. Each one is also an operating system thread that the OS must track and schedule. Tens of thousands of them strain memory, OS limits, and the scheduler.
Here is a small program that does the calculation for you:
public class LittlesLaw {
static long threadsNeeded(double requestsPerSecond, double secondsPerRequest) {
return Math.round(Math.ceil(requestsPerSecond * secondsPerRequest));
}
public static void main(String[] args) {
double[][] cases = {
{100, 0.2},
{1_000, 0.2},
{5_000, 1.0},
{20_000, 1.0}
};
for (double[] c : cases) {
System.out.printf("%,.0f req/s x %.1f s = %,d threads%n",
c[0], c[1], threadsNeeded(c[0], c[1]));
}
}
}Running it prints one line per case, ending with 20,000 req/s x 1.0 s = 20,000 threads.
Thread Pools: Capping the Damage
Creating a new platform thread for every request is slow and can crash the program if too many pile up. So servers use a thread pool. A thread pool is a fixed group of threads that are created once and reused. New requests wait in a queue, a waiting line, until a pool thread becomes free.
A pool protects the machine, but it also sets a hard limit. If the pool has 200 threads, at most 200 requests can be in progress at once. Every other request waits in line.
Seeing the Limit in Action
The program below acts like a tiny server. It has a pool of 10 threads and receives 100 requests. Each request "waits for a database" by sleeping for one second.
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class PoolBottleneck {
public static void main(String[] args) {
int poolSize = 10;
int requests = 100;
Instant start = Instant.now();
try (ExecutorService pool = Executors.newFixedThreadPool(poolSize)) {
for (int i = 0; i < requests; i++) {
int id = i;
pool.submit(() -> {
Thread.sleep(Duration.ofSeconds(1)); // pretend to wait for a database
return id;
});
}
} // close() waits for every submitted task to finish
long seconds = Duration.between(start, Instant.now()).toSeconds();
System.out.println(requests + " requests with " + poolSize
+ " threads took about " + seconds + " seconds");
}
}The output is close to:
100 requests with 10 threads took about 10 secondsThe CPU did almost nothing during those 10 seconds. The work was waiting, not computing. The only thing that made it slow was the shortage of threads: 10 threads could handle only 10 one-second waits at a time, so the 100 requests ran in 10 rounds.
Try changing poolSize to 100. The program now finishes in about 1 second. That suggests an obvious fix: make the pool bigger. The next section explains why that fix breaks down.
Why Not Just Add More Threads?
Raising the pool size works for a while. Then several limits show up.
| Limit | What happens |
|---|---|
| Memory | Each platform thread has its own stack. Thousands of threads can use gigabytes of memory. |
| Operating system caps | The OS limits how many threads a process or user may create. Past that, Java throws `OutOfMemoryError: unable to create native thread`. |
| Scheduling overhead | The OS must switch between threads. With many thousands, more time goes to switching and less to useful work. |
| Startup cost | Creating a platform thread asks the OS for resources, which takes far longer than creating an ordinary Java object. |
So you are stuck in a trade-off. A small pool wastes the CPU, because requests wait in line while the CPU sits idle. A huge pool wastes memory and may crash. Most real servers end up in the middle, with a few hundred threads. That caps throughput well below what the hardware could deliver.
What Happens When Traffic Spikes
Picture a pool of 200 threads, with requests taking 0.2 seconds. By Little's Law, the pool can handle 200 ÷ 0.2 = 1,000 requests per second.
Now the database slows down, and each request takes 1 second. The same 200 threads can now handle only 200 requests per second. If 1,000 requests per second keep arriving, the queue grows by 800 every second. Users see slow pages, then timeouts. The CPU is still mostly idle. The server failed because it ran out of threads, not because it ran out of computing power.
The Other Escape Route: Asynchronous Code
Before virtual threads, Java developers had one main way around this limit: asynchronous programming. In this style, a thread does not wait. It starts an operation, registers a callback (a piece of code to run later when the result arrives), and goes off to handle other work. Libraries built on CompletableFuture and reactive frameworks work this way.
Asynchronous code scales well because a few threads can serve many thousands of requests. But it has real costs:
- The code no longer reads top to bottom. Logic is split into chained calls like
thenApplyandthenCompose. - Stack traces show framework internals instead of your request's steps.
- Debuggers cannot easily step through one request from start to end.
- Ordinary
try/catchand loops must be replaced with special operators.
Developers had to choose between simple code that does not scale and scalable code that is hard to read. Virtual threads aim to remove that choice. They keep the simple thread-per-request style while making each thread cheap enough that you can have one per request, even at very high request rates. The next chapter introduces them.
Summary
- Thread-per-request gives each request its own thread. The code is simple and easy to debug.
- Most request time is spent waiting on I/O, and a blocked platform thread still holds its resources.
- Little's Law (concurrency = throughput × time per request) tells you how many threads you need.
- Platform threads are too costly to create in the tens of thousands, so servers cap them with pools.
- When requests slow down, a capped pool limits throughput while the CPU sits idle.
- Asynchronous code avoids the cap but makes programs harder to write, read, and debug.
Exercise
A service receives 2,000 requests per second, and each request takes 0.5 seconds, mostly waiting for a database. Using Little's Law, how many requests are in progress at once, and what happens if the server uses a fixed pool of 400 platform threads?
Show answer
Concurrency = 2,000 × 0.5 = 1,000 requests in progress at once. A pool of 400 threads can complete only 400 ÷ 0.5 = 800 requests per second, so the queue grows by about 1,200 requests every second. Response times climb until requests time out, even though the CPU is mostly idle.
Exercise
In the PoolBottleneck program, keep poolSize at 10 but change the sleep to 2 seconds and requests to 50. About how long will the program take, and why?
Show answer
About 10 seconds. Only 10 requests run at a time, so 50 requests need 5 rounds, and each round takes 2 seconds. The time comes from the shortage of threads, not from CPU work.
Exercise
Name two reasons why simply setting a thread pool to 100,000 platform threads is not a good fix for thread-per-request scaling.
Show answer
Any two of these: each platform thread reserves its own stack memory, so 100,000 threads can need many gigabytes; the operating system limits how many threads a process can create, which can cause "unable to create native thread" errors; switching between so many OS threads wastes CPU time; and creating platform threads is slow compared with creating ordinary objects.