Scrivio Interview library
DebuggingIntermediate8 min read · updated 12 November 2026

A service creates new Thread(() -> sendEmail(order)).start() for every order. Under a traffic spike it fails with 'java.lang.OutOfMemoryError: unable to create native thread' and the host becomes slow. Explain the failure and fix the design, including whether virtual threads help.

Every new Thread(...) creates a real operating system thread with its own native stack, so one thread per order means thousands of threads during a spike. The error is not about the Java heap: the operating system or the container refuses to create another thread because a process limit or native memory is exhausted. The fix is to stop creating threads per task: hand the work to a bounded executor with a queue and a rejection policy, or better, put the email on a durable queue; virtual threads remove the thread cost but we must still limit how many emails we send at once.

Why this question is asked

Starting a thread per piece of work looks harmless in a code review and works fine at normal traffic. It only fails when traffic jumps, which is the worst possible moment, and it fails in a confusing way: an OutOfMemoryError while the heap graphs look healthy. Interviewers ask this because it tests whether we know what a Java thread costs underneath, and whether we can redesign background work so it is bounded, observable and safe across restarts. In this answer, we will recap what a platform thread is, explain where the error really comes from, fix the design with a bounded executor and with a durable queue, and then see what virtual threads change and what they do not.

1A Quick Recap of What a Thread Costs

A classic Java thread, which the JDK now calls a platform thread, is a thin wrapper around an operating system thread. When we call start(), the JVM asks the operating system to create a real thread, and the operating system reserves a native stack for it. On 64-bit Linux the default Java thread stack size is 1 MB (set with -Xss), and the JVM also allocates some bookkeeping for each thread. This memory lives outside the Java heap, so -Xmx does not limit it and heap graphs do not show it.

The operating system also caps how many threads a user or a process may have. On Linux that includes ulimit -u (the per-user process and thread limit), the kernel-wide threads-max and pid_max settings, and in containers the cgroup pids limit, which Kubernetes and Docker often set to a few thousand. Every one of these limits is reached long before we run out of Java heap.

So the code in the question, new Thread(() -> sendEmail(order)).start(), turns each order into one more operating system thread. Sending an email takes maybe 200 ms to 2 seconds because it waits on an SMTP server or an HTTP API. At 2,000 orders per second with a 1 second email call, about 2,000 threads are alive at any moment, and if the email provider slows down to 10 seconds, that becomes 20,000.

2Where the Error Really Comes From

When start() asks for a new thread and the operating system says no, the JVM throws java.lang.OutOfMemoryError with the message unable to create native thread (newer JDKs add a hint such as possibly out of memory or process/resource limits reached; check your version for the exact wording). The name OutOfMemoryError is misleading: the heap may be half empty. What ran out is the permission or the native memory to create one more thread.

The host becomes slow before the error appears, and the reason is the scheduler. Thousands of threads that are mostly waiting are cheap for the CPU, but the moment responses arrive they all become runnable together, and the kernel spends real time switching between them. Each thread's stack also touches memory, so the machine may start swapping or the container may hit its memory limit. Notice that the failure hurts everything else on the host, not only email sending, because request threads also fail to start.

Step throughHow one thread per order fails under a spike
  1. Order arrivesrequest thread calls new Thread(...).start()
  2. JVM asks the OS for a threadnative stack of about 1 MB reserved
  3. Email call waits on the providerthread stays alive for the whole call
  4. Spike: arrivals exceed completionslive thread count keeps climbing
  5. OS limit or native memory reached?ulimit -u, cgroup pids, memory
  6. OutOfMemoryError: unable to create native threadthe heap may be fine

6 steps in order. Play them, or step through them one at a time.

Nothing in the design limits how many threads exist at once.

We can watch this happen during a load test. A thread dump (jcmd <pid> Thread.print) shows thousands of threads named Thread-1234 all inside sendEmail, and on Linux ls /proc/<pid>/task | wc -l counts the threads of the process directly.

3Fix 1: A Bounded Executor With a Rejection Policy

The first fix is to stop creating threads per task and reuse a small, fixed number of threads. A ThreadPoolExecutor with a fixed size and a bounded queue does exactly that. The pool size limits concurrency, the queue absorbs short bursts, and the rejection policy decides what happens when both are full, so the design has an explicit answer for overload instead of crashing.

Java
ThreadFactory named = Thread.ofPlatform().name("email-", 0).factory();
ThreadPoolExecutor emailPool = new ThreadPoolExecutor(
20, 20, // at most 20 emails in flight
0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(5_000), // at most 5,000 waiting
named,
new ThreadPoolExecutor.CallerRunsPolicy()); // when full, slow the caller down
emailPool.execute(() -> sendEmail(order)); // threads alive: 20, never 20,000

CallerRunsPolicy runs the task on the submitting request thread when the pool and queue are full, which slows down intake and acts as back-pressure. In a web service we might prefer AbortPolicy and a clear error, or a custom handler that records the order for a later retry. The important change is that the worst case is now a known number of threads and a known number of queued tasks.

But there is a catch: the queue lives in memory. If the instance is redeployed or crashes, the 5,000 queued emails disappear without a trace. For a confirmation email that may be acceptable; for anything the business cares about, it is not.

4Fix 2: Move Email Sending to a Durable Queue

The more robust design treats the email as a fact to record, not as work to do right now. In the same database transaction that saves the order, we insert a row into an outbox table (the transactional outbox pattern), or we publish a message to Kafka or a message broker. A separate consumer with a fixed concurrency reads the queue, sends the email, and marks it done. If the consumer crashes, the message is still there and is retried.

This also separates the user's request from the email provider's speed. The order request finishes in milliseconds whether the provider is fast, slow or down, and a backlog during a spike simply drains later. We get retries with back-off, a dead-letter queue for poison messages, and a backlog size we can alert on.

5Do Virtual Threads Help?

Virtual threads, final since Java 21, are threads managed by the JVM instead of the operating system. Many virtual threads run on a few carrier platform threads, and when a virtual thread blocks on I/O, the JVM unmounts it and the carrier runs another one. Their stacks live on the heap and start at a few hundred bytes, so creating a million of them is fine. With Executors.newVirtualThreadPerTaskExecutor(), the operating system thread limit stops being the problem.

Java
Semaphore emailPermits = new Semaphore(50); // what the provider can take
try (ExecutorService vexec = Executors.newVirtualThreadPerTaskExecutor()) {
vexec.submit(() -> {
emailPermits.acquire(); // waits cheaply when 50 are busy
try { sendEmail(order); }
finally { emailPermits.release(); }
return null;
});
}

Notice what virtual threads do not fix. Our email provider still accepts only so many connections or requests per second, so 20,000 concurrent sends would just move the failure to the provider, which starts returning 429 Too Many Requests or timing out. That is why we keep a Semaphore or a rate limiter around the call. Virtual threads also keep work in memory, so they do not replace a durable queue for work that must survive a restart.

6Do Not Lose Errors and Work on Shutdown

A fire-and-forget thread has two more problems. If sendEmail throws, the exception goes to the thread's uncaught exception handler, which by default prints a stack trace to stderr and nothing else, so failures are silent. And when the application shuts down, nobody waits for those threads, so emails in progress are cut off.

Managed executors fix both. In Spring we define the pool as a bean (a ThreadPoolTaskExecutor or a virtual-thread executor), log or count failures in the task, and configure graceful shutdown so the executor stops taking new work and waits for running tasks, for example with setWaitForTasksToCompleteOnShutdown(true) and an await termination period. Executor metrics such as active threads, queue size and rejections then tell us how close we are to the limit before customers notice.

7Follow-up questions

Why does the heap look fine when the error says OutOfMemoryError?

Because the memory or permission that ran out is outside the heap. Thread stacks are native memory reserved by the operating system, and thread counts are capped by ulimit and cgroup pids limits. The JVM reports a failed thread creation as an OutOfMemoryError for historical reasons, so the first step in diagnosis is to count threads, not to raise -Xmx. Raising -Xmx can even make it worse, because the heap takes native memory that thread stacks could have used.

Would reducing -Xss to 256k fix the problem?

It would move the limit, not remove it. Smaller stacks let more threads fit into memory, but the thread count limit still applies, the scheduler still struggles with thousands of runnable threads, and deep call stacks may now fail with StackOverflowError. The real fix is to bound concurrency, so the number of threads no longer grows with traffic.

Is CallerRunsPolicy always a good choice?

It is a simple form of back-pressure, but it makes the caller do the slow work. In a web request that means the user waits for an email to be sent, and Tomcat request threads become busy with email calls. For request-driven work, rejecting quickly and recording the task for a retry, or using a durable queue from the start, usually gives better behaviour.

8Conclusion

In this answer, we saw that new Thread per order creates one operating system thread per task, so a spike exhausts thread limits or native memory and the JVM reports OutOfMemoryError: unable to create native thread even though the heap is fine. We fixed the design with a bounded executor and an explicit rejection policy, and for important work with a durable queue that survives restarts. Virtual threads make threads cheap, but we still limit concurrency to the email provider with a Semaphore or rate limiter, and we use managed executors so errors are seen and shutdown is graceful.

What to say in the interviewAbout 90 seconds aloud

Open with

This error is not a heap problem. Every new Thread is a platform thread backed by an operating system thread with its own native stack, around 1 MB reserved by default.

Then, if they want more

Creating one per order means the thread count grows with traffic and with the email provider's latency, so during a spike we hit the user process limit, the container's pids limit, or native memory, and start() fails with unable to create native thread. Before that, the host slows down because thousands of threads compete for the scheduler and memory.

To fix it, I would first stop creating threads per task and submit to a bounded executor: a fixed number of threads, a bounded queue, and an explicit rejection policy.

For email, which the business cares about, I would go further and write it to an outbox table or a message queue in the same transaction as the order, with a consumer that retries and has a dead-letter queue, so nothing is lost on restart.

Virtual threads help with the thread cost, since they are cheap and the OS limit disappears, but the email provider still has a limit, so I would wrap the call in a Semaphore or rate limiter. And I would use managed executors so exceptions are logged and counted and shutdown waits for running work.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A service creates new Thread(() -> sendEmail(order)).start() for every order. Under a...": https://scrivio-interview-library.netlify.app/java/threads/4c9bdaba96/