Home โบ Java exceptions โบ StackOverflowError
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.StackOverflowErrorExtends 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
- Recursion with no base case, or a base case that is never reached.
- Two objects whose
toString,equalsorhashCodecall each other, such as bidirectional JPA entities printed with Lombok@Data. - Jackson serialising a cycle: a parent that holds children that hold the parent.
- A very deep but finite structure (a long linked list, a deeply nested expression) processed recursively.
How to fix it
- Look at the repeating frames in the trace to find the cycle, then add or correct the base case.
- Break object cycles:
@JsonIgnoreor@JsonManagedReference/@JsonBackReference, and exclude the back-reference fromtoString. - Rewrite deep recursion with a loop and an explicit stack (Deque).
- Raise
-Xssonly as a last resort and only for known deep but finite work, since it applies to every thread.
Broken and fixed
int factorial(int n) {
return n * factorial(n - 1); // never stops
}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.