The Hidden Cost of Java Platform Threads: Memory, OS Limits and Context Switches
Why the thread-per-request model hits a wall with platform threads: stack memory per thread, OS thread limits, context-switch overhead, and what throughput really measures. Includes a measured experiment and how to find your own machine's limits.
kvi5hnuCode Sprout team member9 min readOn this page
Most Java server code is written in the thread-per-request style: one thread handles one request from start to finish. The style is popular because it's simple. The code reads top to bottom, local variables hold the request's state, and a stack trace shows exactly where a request is. The trouble is the price of each thread. This article looks at what a platform thread really costs, and why simply adding more threads stops working.
Thread-per-request in a servlet container
Servers such as Tomcat and Jetty keep a pool of worker threads. When a request arrives, the container takes a free thread from the pool, and that thread runs your handler, including every database query and remote call it makes, until the response is written. Then the thread goes back to the pool.
A typical handler doesn't compute much. It spends most of its time waiting for other systems:

While a thread waits for the database, it can't serve anyone else. With 200 pool threads and requests that each take 100 ms mostly waiting, the server tops out at about 2,000 requests per second, even if the CPU is 90% idle. The obvious fix is more threads. That works for a while, but platform threads are expensive in three ways.
Throughput: what we're trying to raise
Throughput is the rate at which a system completes work:
It's usually quoted in requests per second. It differs from latency, which is how long one request takes. A server can have excellent latency (each request takes 50 ms) and poor throughput (it can only handle 40 at once), or the reverse. Threads raise throughput by letting more requests be in progress at the same time. Article 10 makes the relationship exact with Little's Law: in-progress requests = throughput × latency.
Cost 1: memory for each thread's stack
Every platform thread gets its own stack, allocated outside the Java heap. The default maximum size is typically 1 MiB on 64-bit x86 Linux and Windows, and 2 MiB on ARM64 systems such as Apple silicon Macs. You can check your JVM with:
java -XX:+PrintFlagsFinal -version | grep ThreadStackSize
The value is in KiB, and -Xss (or -XX:ThreadStackSize) changes it.
That size is reserved address space, not memory used up front. The OS commits pages only as the stack grows. Measuring 500 idle platform threads on JDK 25 (macOS, Apple silicon) with Native Memory Tracking shows the difference:
java -XX:NativeMemoryTracking=summary ... then: jcmd <pid> VM.native_memory summary scale=KB
Thread (reserved=1079068KB, committed=42332KB)
(threads #526)
(stack: reserved=1077248KB, committed=40512KB, ...)
So about 2 MiB reserved but only about 80 KiB committed per thread, because these threads have shallow stacks. Real request threads run deep framework call chains and commit far more, often hundreds of KiB each, and a thread that once ran a deep stack keeps those pages. Ten thousand such threads can easily need several gigabytes outside the heap, which counts against a container's memory limit. If physical memory runs out, the OS starts swapping, and performance collapses, since disk is orders of magnitude slower than RAM.
Cost 2: the operating system's thread limit
A Java platform thread is a thin wrapper around one OS thread, so the OS decides how many you can have. Limits come from several places:
- per-user process/thread limits (
ulimit -uon Linux and macOS); - system-wide limits such as Linux's
/proc/sys/kernel/threads-max; - the
pidslimit of a container (Docker and Kubernetes often set one), which counts threads; - the address space and memory available for stacks.
When Thread.start() can't get a native thread, it throws OutOfMemoryError: unable to create native thread. Despite the name, the heap may be nearly empty. This program finds the limit by starting parked threads until creation fails:
import java.util.concurrent.locks.LockSupport;
public class ThreadCeiling {
public static void main(String[] args) {
int created = 0;
try {
while (true) {
Thread.ofPlatform().daemon(true).start(LockSupport::park);
created++;
}
} catch (OutOfMemoryError e) {
System.out.println("Platform threads created before failure: " + created);
System.out.println(e.getMessage());
}
}
}
Typical results are a few thousand to a few tens of thousands of threads, depending on the OS, its configuration and the memory available. Compare that with the hundreds of thousands of concurrent connections a modern OS can keep open: the thread limit is reached long before the network limit.
Cost 3: context switches
When a core changes from running one thread to running another, the OS performs a context switch: it saves the registers and state of the old thread, picks the next thread, and restores its state. A switch takes on the order of a few microseconds directly, and it has an indirect cost too, because the new thread's data is usually not in the CPU caches, so it runs slowly for a while.
A few switches per second don't matter. Thousands of busy threads competing for a handful of cores do: the CPU spends more and more of its time switching instead of working. Context switches also happen every time a blocked thread wakes up, which in a thread-per-request server is several times per request.
Creation cost
Creating a platform thread means a system call, allocating a stack and registering it with the scheduler: tens of microseconds. That's cheap compared with a network call, but expensive compared with an ordinary method call. It's one reason servers keep threads in pools and reuse them, instead of creating one per request.
Seeing blocked threads hold resources
You can watch the cost of waiting threads without hitting any limits. This program starts 500 platform threads that block on a latch, the way request threads block on I/O, and asks the JVM's thread management bean how many threads exist:
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Solution {
public static void main(String[] args) throws InterruptedException {
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
int before = threads.getThreadCount();
int count = 500;
CountDownLatch allStarted = new CountDownLatch(count);
CountDownLatch release = new CountDownLatch(1);
List<Thread> waiting = new ArrayList<>();
for (int i = 0; i < count; i++) {
Thread t = Thread.ofPlatform().name("waiter-" + i).start(() -> {
allStarted.countDown();
try {
release.await(); // block, like a thread waiting on I/O
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
waiting.add(t);
}
allStarted.await();
int during = threads.getThreadCount();
System.out.println("extra live OS-backed threads: " + (during - before));
System.out.println("each one is blocked: "
+ waiting.stream().allMatch(t -> t.getState() == Thread.State.WAITING));
release.countDown();
for (Thread t : waiting) t.join();
System.out.println("all finished: " + waiting.stream().noneMatch(Thread::isAlive));
}
}
Output:
extra live OS-backed threads: 500
each one is blocked: true
all finished: true
All 500 threads exist as OS threads, each with its own stack, and none of them is doing anything. That's the situation of a thread-per-request server under load: plenty of threads, mostly idle, and still not enough of them.
Three ways out
The rest of Part 1 follows the historical answers to this problem:
- Do more within one request. Run a request's independent waits in parallel, so each request holds its thread for less time (articles 4 and 5).
- Don't hold a thread while waiting. Asynchronous and reactive styles return the thread to a pool during I/O and continue in a callback (articles 6 and 7). This scales, but makes code much harder to write and debug.
- Make threads cheap. Virtual threads keep the simple blocking style but cost a few hundred bytes to a few KiB each, and release their OS thread while they wait (Part 2).
What's current
- Thread stack defaults haven't changed in many releases. Measure them with
-XX:+PrintFlagsFinaland Native Memory Tracking on the JDK and OS you deploy to, rather than relying on folklore. - Container platforms commonly cap the number of processes and threads per container. Check your orchestrator's
pidslimit before raising thread pool sizes. - Virtual threads (Java 21+) don't use a fixed-size native stack. Their stack frames live on the Java heap and grow and shrink as needed.
Common questions
Why does running out of threads throw OutOfMemoryError when the heap is almost empty?
Thread stacks are native memory, not heap. The error reports that the OS refused to create a native thread, which can be caused by a thread-count limit as well as by a lack of memory. Read the message: unable to create native thread is a thread problem, not a heap problem.
Can I just make thread stacks smaller with -Xss?
You can, and it lets you create more threads. But code with deep call chains (frameworks, recursion) then fails with StackOverflowError, and the other costs (OS limits, context switches) remain. It's a tuning knob, not a fix.
Is a blocked thread using CPU?
No. A thread blocked on I/O, a lock or sleep isn't scheduled. It uses memory and kernel resources, not CPU time. The CPU cost comes when it wakes up (a context switch) and when many runnable threads compete for cores.
Doesn't a thread pool fix the creation cost? It fixes the creation cost and caps the total number of threads. But a pool doesn't change the main problem: each pooled thread is still held for the whole request, including all its waits.
Summary
- Thread-per-request is easy to write and debug, but each request holds a platform thread for its entire duration, mostly while waiting.
- Throughput is completed work per unit of time. Holding more requests in progress raises it, until a resource runs out.
- Platform threads cost native stack memory (1–2 MiB reserved each, committed on demand), are capped by OS and container limits, and add context-switch overhead.
- Thread creation failure shows up as
OutOfMemoryError: unable to create native thread. - The industry's answers were parallel fan-out, asynchronous code and, finally, cheap virtual threads.
Practice questions
A service has a pool of 100 platform threads. Each request takes 250 ms, of which 230 ms is waiting on remote services. What is the maximum throughput, and what is limiting it?
Answer
At most 100 requests in progress, each lasting 0.25 s, gives 100 / 0.25 = 400 requests per second. The limit is the number of threads, not the CPU: each request uses only 20 ms of CPU, so the cores are mostly idle.
A program fails with java.lang.OutOfMemoryError: unable to create native thread, but monitoring shows the heap is 30% full. Name two likely causes.
Answer
The process hit an OS or container limit on threads (for example ulimit -u or a container pids limit), or there isn't enough native memory or address space left for another thread stack. Increasing the heap (-Xmx) doesn't help and can make it worse by leaving less native memory.
Why does the measured "committed" stack memory per idle thread come out much lower than the 2 MiB stack size?
Answer
The stack size is a reservation of address space. The OS commits physical pages only when the thread actually uses that part of its stack. Idle threads with shallow call chains touch only a few pages, while threads running deep framework code commit much more.
Previous: Java Threads: Creating and Starting Them, and Why start() Is Not run()
Next: Blocking I/O and Parallel Fan-Out in Java: Speeding Up a Request With Raw Threads

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.