StackOverflowError in Java: reading a truncated trace, finding the loop, and when -Xss is the right fix

A request fails, the log shows java.lang.StackOverflowError, and below it come a thousand lines that all look the same: two or three methods calling each other over and over. The interesting part, the frame that started the loop, is not there. This guide explains what the error means in HotSpot, why the trace hides its own beginning, and how to fix the cause instead of buying a bigger stack.
What actually overflows
Every Java thread has a stack: one frame per method call in progress, holding local variables, operands and the return address. For a platform thread, the maximum size of that stack is fixed when the thread starts. It comes from -Xss (the same setting as -XX:ThreadStackSize), and the java command reference gives the defaults: 1024 KB on Linux/x64 and macOS/x64, 2048 KB on Linux/AArch64 and macOS/AArch64, while on Windows the default depends on virtual memory. The same stack also holds the native frames of any JNI code the thread runs, a point covered in the guide to unable to create native thread.
HotSpot does not wait for the stack to be literally full. It keeps guard zones at the end of each thread stack and checks, on method entry, that the new frame plus a safety margin still fits. JEP 270 calls this the "stack-banging" mechanism: it lets the JVM report the overflow cleanly as an error thrown at a method call, while preserving its own integrity. The sizes of these zones are visible in the final flags:
java -XX:+PrintFlagsFinal -version | grep -E 'ThreadStackSize|Stack(Shadow|Yellow|Red|Reserved)Pages'
On our OpenJDK 21 build for Linux x64 this printed ThreadStackSize = 1024, StackShadowPages = 20, StackYellowPages = 2, StackRedPages = 1 and StackReservedPages = 1. None of these needs tuning; they explain why a thread overflows a little before its nominal limit.
How deep is "too deep"?
There is no fixed number of frames. The depth depends on the size of each frame, and that changes with the method's locals and parameters and with whether the JIT has compiled it yet. We ran a trivial recursive method that only increments a counter, then a variant with four long parameters, on the same JDK 21 machine:
| Configuration | Depth reached at StackOverflowError |
|---|---|
| Default stack (1 MB), main thread, four runs | 21,904 to 22,292 |
Default stack, interpreter only (-Xint) | 10,730 |
Default stack, method with four long parameters | 9,656 |
-Xss512k, main thread | 10,192 |
-Xss2m, main thread | 48,346 |
Default flags, thread created with a 4 MB stackSize | 242,633 |
Two lessons follow. First, the same code can fail at different depths from one run to the next, because compiled frames are smaller than interpreted ones and compilation timing varies. A recursion that "usually works" with 20,000 levels is one deployment away from failing. Second, the depth scales roughly with the stack size, so doubling -Xss buys roughly double the depth. That is useful for legitimately deep algorithms and useless against infinite recursion, which will exhaust any stack.
Virtual threads overflow too. Their frames live on the heap while they are unmounted, but the depth is still bounded: in our runs a virtual thread failed in the same range as a platform thread (20,766 to 21,994 frames with default flags) and followed -Xss when we changed it. The basics of virtual threads are in virtual threads in production.
Why the trace stops at 1024 lines
When the error is thrown, the JVM records at most MaxJavaStackTraceDepth frames, 1024 by default. It keeps the frames nearest to the point of failure, which in a runaway recursion are all copies of the loop. Our test program, in which main calls entry, which starts an a/b ping-pong, printed this:
Exception in thread "main" java.lang.StackOverflowError
at Top.b(Top.java:1)
at Top.a(Top.java:1)
at Top.b(Top.java:1)
... (1024 lines in total, every one a or b)
entry and main never appear. To see where the loop was entered, reproduce the failure with a larger limit, for example -XX:MaxJavaStackTraceDepth=100000; with it, our trace held all 22,091 frames, and the last lines showed the caller. On JDK 21 a value of 0 also recorded the whole stack, but an explicit large number states the intent more clearly. Do not leave a huge limit on in production: every exception, not only this one, would pay for filling and printing its trace.
Two other tricks help without a restart. The repeating cycle itself, read from the top of the trace, usually names the classes involved; and a thread dump taken while a request is slowly descending into deep recursion shows the full stack, bottom included, because jstack and jcmd Thread.print are not subject to the exception limit.
The usual suspects in production
- Cyclic object graphs. A parent that lists its children, children that point back to the parent, and a generated
toString,equalsorhashCodethat walks both directions. The trace alternates between the two classes' methods. Exclude the back-reference from these methods. - Serialisation of the same cycles. JSON or XML mappers that follow references will recurse until the stack gives out; Jackson, for example, wraps the error in a mapping exception that mentions infinite recursion. Annotate the back-reference or serialise a dedicated DTO.
- Regular expressions on long input.
java.util.regexmatches some patterns recursively, one level per repetition. In our test,"ab".repeat(n/2).matches("(a|b)*")succeeded for 1,000 characters and threwStackOverflowErrorfrom 5,000 characters on, while the equivalent character class[ab]*matched 200,000 characters without trouble. Prefer character classes to alternations of single characters, and cap the length of untrusted input before matching. - Accidental self-calls. A delegating method that calls itself after a refactoring, a proxy or interceptor that re-enters the bean it wraps, an overloaded method that resolves to itself. The trace then shows a single method repeated.
- Genuinely deep data. Recursive descent over a very deep tree or a long linked structure. Here the code is correct and only the input is unusual.
Can you catch it?
Technically yes, as our test did, but treat it like other errors rather than as control flow. JEP 270 explains why: the error can be thrown at any method call, including in the middle of updating a data structure, and before that JEP a ReentrantLock could be left locked with no owner. JEP 270 adds a reserved area so that annotated critical sections in the JDK can finish, but it explicitly does not protect application code. After a StackOverflowError, log it, fail the request and let the thread's work end; do not retry the same input in a loop.
When to change the stack size
- First, fix the recursion. If the cycle is infinite, no stack is big enough. Most production cases end here.
- Turn deep recursion into iteration with an explicit
ArrayDequewhen the depth depends on input you do not control. - Give a big stack to one thread, not to all. The
Threadconstructor that takes astackSizeargument, or a thread factory built on it, raises the limit only for the worker that parses deep documents. The Javadoc warns that on some platforms the value may be ignored; on Linux x64 it worked, as the table shows. - Raise
-Xssglobally last. It applies to every platform thread, so the reservation is multiplied by the thread count. Stack pages are generally committed only as they are used, but the address space and the limits discussed in unable to create native thread are not, and lowering-Xssto fit more threads simply brings this error back.
A bigger stack moves the failure further away; it does not make an infinite loop finite.
Sources
- Oracle, The java Command, JDK 21 (
-Xssand-XX:ThreadStackSize, default stack sizes per platform) - OpenJDK, JEP 270: Reserved Stack Areas for Critical Sections (stack banging, StackOverflowError in critical sections, the ReentrantLock case)
- Depths, flag values, trace lengths and regular-expression results: our own runs of OpenJDK 21.0.12 on Linux x64, 19 November 2026; the
Thread(ThreadGroup, Runnable, String, long)Javadoc for the per-thread stack size
Threads & CPUUnable to create native thread
Usually not a heap problem: which operating-system limit was hit, how to prove it, and how to find the pool that keeps growing.
Threads & CPUReading thread dumps
Take a series, read states and lock lines, and let the JVM point out deadlocks for you.
Threads & CPUVirtual threads in production
Carriers, pinning before and after JDK 24, why not to pool them, and how to see them in dumps and JFR.