BackendBench
Coffee

Home โ€บ Java exceptions โ€บ StackOverflowError

Error ยท java.lang

StackOverflowError: causes and fixes

A thread used up its call stack, almost always because of unbounded or very deep recursion.

What it looks like

java.lang.StackOverflowError

Extends VirtualMachineError in java.lang.

What it means

Each method call adds a frame to the thread's stack, which has a fixed size (typically 512 KB to 1 MB, set with -Xss). When the stack is full the JVM throws StackOverflowError. The stack trace is a few lines repeated thousands of times, and the repeating lines show you the recursion. It is an Error, not an Exception, so ordinary catch (Exception e) blocks do not catch it.

Common causes

How to fix it

  1. Look at the repeating frames in the trace to find the cycle, then add or correct the base case.
  2. Break object cycles: @JsonIgnore or @JsonManagedReference / @JsonBackReference, and exclude the back-reference from toString.
  3. Rewrite deep recursion with a loop and an explicit stack (Deque).
  4. Raise -Xss only as a last resort and only for known deep but finite work, since it applies to every thread.

Broken and fixed

fails
int factorial(int n) {
    return n * factorial(n - 1); // never stops
}
works
int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

In JPA, @Data on entities with bidirectional relationships generates toString and hashCode that recurse forever. Use @ToString.Exclude and @EqualsAndHashCode.Exclude on the back-reference.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is StackOverflowError a checked or unchecked exception?

StackOverflowError is an Error (it extends VirtualMachineError). Errors signal serious problems in the JVM or environment; applications normally should not catch them, and ordinary catch (Exception e) blocks will not.

Which package is StackOverflowError in?

It lives in java.lang, so the import is import java.lang.StackOverflowError; (java.lang needs no import).

What is the first thing to check when I see StackOverflowError?

Read the message and the first stack trace line in your own code. The usual causes are: Recursion with no base case, or a base case that is never reached; and Two objects whose toString, equals or hashCode call each other, such as bidirectional JPA entities printed with Lombok @Data.

Related exceptions

More tools you might need