Threads & CPU

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

Threads & CPU · · Published 2026-11-19

A small cairn of six stacked sandstone rocks standing on a flat slab of bare rock under a clear blue sky, with juniper trees in the background
Every call adds a stone; the stack has a fixed height, and the last stone does not fit. Photo: Jennifer Bourn, WordPress Photo Directory, CC0.

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:

ConfigurationDepth reached at StackOverflowError
Default stack (1 MB), main thread, four runs21,904 to 22,292
Default stack, interpreter only (-Xint)10,730
Default stack, method with four long parameters9,656
-Xss512k, main thread10,192
-Xss2m, main thread48,346
Default flags, thread created with a 4 MB stackSize242,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

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

  1. First, fix the recursion. If the cycle is infinite, no stack is big enough. Most production cases end here.
  2. Turn deep recursion into iteration with an explicit ArrayDeque when the depth depends on input you do not control.
  3. Give a big stack to one thread, not to all. The Thread constructor that takes a stackSize argument, 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.
  4. Raise -Xss globally 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 -Xss to 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