Quick revision
The short answer
Every thread has a stack of fixed size, and each method call pushes a frame onto it; StackOverflowError is thrown when a chain of nested calls needs more frames than fit. In production it usually comes from unbounded or very deep recursion, from cyclic toString, equals or hashCode between objects that refer to each other, or from serializing bidirectional relationships to JSON. The real fix is to convert the recursion to a loop with an explicit stack, bound its depth, or break the cycle; raising the stack size with -Xss only hides the cause.
What to remember
In this answer, we saw that StackOverflowError happens when nested calls need more frames than a thread's fixed-size stack holds. The usual causes are deep or unbounded recursion, cyclic toString, equals or hashCode, and serializing bidirectional relationships. We fix it by converting recursion to a loop with an explicit stack, bounding depth, or breaking cycles with exclusions or DTOs. Raising -Xss or the thread's stackSize only hides the cause, and since it is an Error that can leave state inconsistent, we treat it as a bug rather than something to recover from.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Every thread has a stack of fixed size, and each method call pushes a frame onto it; StackOverflowError is thrown when a chain of nested calls needs more frames than fit. In production it usually comes from unbounded or very deep recursion, from cyclic toString, equals or hashCode between objects that refer to each other, or from serializing bidirectional relationships to JSON. The real fix is to convert the recursion to a loop with an explicit stack, bound its depth, or break the cycle; raising the stack size with -Xss only hides the cause.
Why this question is asked
StackOverflowError is one of the first errors every Java developer meets, usually as a recursive method without a base case. In production it is less obvious: a service works for months and then fails on one customer's unusually deep category tree, or a new Lombok annotation on two entities makes every log statement blow up. Interviewers ask about it to check that we understand how the call stack works and that we fix the shape of the code rather than turning up a JVM flag. In this answer, we will recap the call stack, reproduce the error, look at the common causes, and go through the fixes, including what happens to the application after the error.
1A Quick Recap of the Call Stack
Each Java thread has its own call stack, a region of memory where the JVM keeps one frame for every method that has been called and has not yet returned. A frame holds the method's local variables, its parameters and some bookkeeping such as where to return to. When a method calls another, a new frame is pushed on top; when it returns, its frame is popped.
The stack has a fixed maximum size, decided when the thread starts. On 64-bit Linux the default for platform threads is usually 1 MB, set by the -Xss option (check your platform, since defaults vary). How many frames fit depends on how big each frame is, but typical numbers are in the thousands to tens of thousands. When a call needs a new frame and there is no room left, the JVM throws StackOverflowError.
2Reproducing It
A recursive method that walks a tree is the classic example. It works perfectly on normal data and fails on unusual data.
Notice the stack trace: the same line repeated over and over. That repetition is the signature of a StackOverflowError, and the repeated lines tell us exactly which methods form the loop. The JVM limits how many frames it records in the trace (1,024 by default), so we see the repeating part, not where it started.
3The Common Causes in Production
Deep recursion on real data is the first cause: tree walks, recursive descent parsers, graph searches, or a recursive method whose base case is never reached because of a bug, such as comparing objects with == instead of equals.
The second cause is cyclic toString, equals or hashCode. Suppose Order has a list of OrderLine objects and each OrderLine points back to its Order. If both classes generate toString from all fields, which Lombok's @Data or @ToString does by default, then printing an order prints its lines, each line prints its order, which prints its lines again, forever. The same loop happens with equals and hashCode, so even putting such an entity in a HashSet can overflow.
The third cause is the same cycle in JSON serialization. When Jackson serializes the Order, it follows lines, then order, then lines, and so on. Jackson detects the overflow and reports it as a JsonMappingException that mentions infinite recursion and wraps the StackOverflowError (check your Jackson version for the exact type and message).
- Order.toString()prints its fields, including lines
- OrderLine.toString()prints its fields, including order
- Order.toString() againthe same order, one frame deeper
- Repeat until the stack is full
StackOverflowError
4 steps in order. Play them, or step through them one at a time.
4Fix 1: Convert Recursion to Iteration
The general fix for deep recursion is to keep our own stack in a data structure on the heap, which can grow to millions of entries, and loop instead of calling ourselves.
The reason this works is that the pending work now lives in an ArrayDeque on the heap instead of in stack frames. The heap is typically hundreds of megabytes or more, and each entry is small, so depth is no longer limited by the thread stack.
5Fix 2: Bound the Depth or Break the Cycle
Sometimes recursion is the clearest code and the data has a natural limit. Then we enforce that limit explicitly and fail with a clear message, such as rejecting a JSON document nested more than 100 levels deep or a category tree deeper than 50. Many parsers already do this: Jackson 2.15 and later, for example, has a configurable maximum nesting depth (check your version).
For cycles, we break the loop. In entities we exclude the back reference from toString, equals and hashCode, for example with @ToString.Exclude and @EqualsAndHashCode.Exclude in Lombok, or by writing equals and hashCode on the ID only. For JSON, we return DTOs instead of entities, which is the cleanest choice, or mark the relationship with @JsonManagedReference and @JsonBackReference, or @JsonIgnore on the back reference.
6Raising the Stack Size, and What Happens After the Error
We can give threads a larger stack with -Xss, for example -Xss4m, or for one thread with the Thread constructor that takes a stackSize argument, or Thread.ofPlatform().stackSize(...) since Java 21. That is occasionally right for a known deep algorithm on a dedicated thread. As a general fix it is wrong: -Xss applies to every thread, so 500 threads with 4 MB each reserve 2 GB of address space, and the input that overflowed at depth 10,000 will overflow at 40,000 next month.
StackOverflowError extends VirtualMachineError, an Error rather than an Exception, so ordinary catch (Exception e) blocks do not catch it. After it is thrown, the stack unwinds and frames are freed, so the thread can technically continue, and a request thread in a web server usually does. But the error can strike in the middle of any method, including inside a library while it holds a lock or has updated half of a data structure. So we treat it as a bug to fix, not a condition to recover from, and we never catch it to carry on as normal.
7Follow-up questions
Why does the trace show only about a thousand frames?
The JVM records at most a fixed number of frames per stack trace, 1,024 by default, set with -XX:MaxJavaStackTraceDepth. For a StackOverflowError that is enough to see the repeating cycle, which is what we need to find the cause.
Do virtual threads change this?
Virtual threads, final since Java 21, keep their stacks on the heap as chunks and can grow them, but they are still limited by the maximum stack size, so infinite recursion still ends in StackOverflowError. Deep recursion on a virtual thread also makes it expensive to park and resume, because its stack has to be copied.
8Conclusion
In this answer, we saw that StackOverflowError happens when nested calls need more frames than a thread's fixed-size stack holds. The usual causes are deep or unbounded recursion, cyclic toString, equals or hashCode, and serializing bidirectional relationships. We fix it by converting recursion to a loop with an explicit stack, bounding depth, or breaking cycles with exclusions or DTOs. Raising -Xss or the thread's stackSize only hides the cause, and since it is an Error that can leave state inconsistent, we treat it as a bug rather than something to recover from.
Open with
Every thread has a call stack of fixed size, usually about 1 MB by default on 64-bit Linux, and each method call pushes a frame with its locals and parameters.
Then, if they want more
StackOverflowError is thrown when nested calls need more frames than fit.
In production the causes I usually see are recursion that is unbounded or just deeper than expected on real data, like a long chain in a tree, and cycles: two entities that reference each other with generated toString, equals or hashCode, for example Lombok @Data on a bidirectional JPA relationship, or Jackson serializing that relationship.
The stack trace gives it away, because the same few lines repeat. To fix deep recursion, I convert it to iteration with an explicit stack, like an ArrayDeque, which lives on the heap, or I enforce a maximum depth and fail with a clear message.
For cycles, I exclude the back reference from toString and equals, and return DTOs instead of entities in APIs. I can raise the stack size with -Xss or the Thread constructor's stackSize parameter, but that applies to every thread and only moves the limit, so it hides the problem.
It is an Error, not an Exception, and although the thread can continue after the stack unwinds, state may be half-updated, so I treat it as a bug to fix.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "What causes StackOverflowError, and how can you fix deep recursion that triggers it in...": https://scrivio-interview-library.netlify.app/java/exceptions/b85ca1a790/