java.lang.StackOverflowError
ID: java/stackoverflowerror
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 17 | active | — | — | — |
Root Cause
StackOverflowError occurs when the thread's call stack exceeds its maximum depth, almost always caused by unbounded recursion. The stack trace will show repeating method call patterns.
genericWorkarounds
-
92% success Examine the stack trace for repeating call patterns and fix the base case or cycle in the recursion
1. Look at the stack trace — you will see a repeating sequence of method calls. 2. Identify the entry point of the recursive cycle. 3. Common causes: missing base case in recursive algorithm, toString()/hashCode()/equals() calling themselves through circular object references, JPA/Hibernate bidirectional relationship toString(), Jackson serialization of circular references. 4. Fix by adding the proper base case, breaking the circular reference, or using @JsonIgnore/@ToString.Exclude on bidirectional fields.
-
90% success Convert deep recursion to an iterative approach using an explicit stack data structure
1. Replace the recursive method with a while loop. 2. Use a java.util.Deque<State> (ArrayDeque) as an explicit stack to hold intermediate state. 3. Push initial state, then loop: pop, process, push new states as needed. 4. This uses heap memory instead of thread stack memory, which is much more abundant and configurable. 5. For tree traversals, consider using BFS with a Queue instead of recursive DFS.
Dead Ends
Common approaches that don't work:
-
Increasing the stack size with -Xss to accommodate deeper recursion
60% fail
Increasing -Xss is a temporary workaround. If the recursion is genuinely unbounded (e.g., infinite loop due to a missing base case), no stack size will be sufficient. Even if the recursion is bounded but deep, larger stacks multiply memory usage per thread, which can cause heap OOM in multi-threaded applications.
-
Catching StackOverflowError to continue execution
85% fail
After a StackOverflowError, the thread's stack is in a fragile state. Any further method calls can trigger another StackOverflowError. The application state is likely inconsistent since the recursive operation did not complete. Catching this error leads to unpredictable behavior.