Quick revision
The short answer
Every recursive call takes a frame on the thread's stack, and a stack of typically 512 KB to 1 MB runs out long before 40,000 nested calls. The JVM does not eliminate tail calls, so rewriting the method in tail-recursive form does not help. The real fix is an iterative traversal with an explicit ArrayDeque, which moves the pending work to the heap, plus a visited set to catch cycles; a bigger -Xss or a thread with a larger stack is only a stopgap.
What to remember
In this answer, we saw that each recursive call uses a stack frame and a thread's stack, often 512 KB to 1 MB, holds only tens of thousands of them, so 40,000 nested categories overflow. The JVM does not eliminate tail calls, so tail-recursive rewriting does not help. The fix is an iterative walk with an ArrayDeque that keeps pending work on the heap and a visited set that stops cycles; larger stacks via -Xss or a Thread constructor are a stopgap; and the import should reject cycles and absurd depths before the data is stored.
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 recursive call takes a frame on the thread's stack, and a stack of typically 512 KB to 1 MB runs out long before 40,000 nested calls. The JVM does not eliminate tail calls, so rewriting the method in tail-recursive form does not help. The real fix is an iterative traversal with an explicit ArrayDeque, which moves the pending work to the heap, plus a visited set to catch cycles; a bigger -Xss or a thread with a larger stack is only a stopgap.
Why this question is asked
Recursive tree walks are short and pleasant to write, and they work for years until one customer's data is shaped differently. Interviewers ask this question because it tests whether we know where recursion keeps its state, why Java behaves differently from functional languages here, and whether we fix the root cause or just make the error go away. In this answer, we will recap what a stack frame is, reproduce the failure, see why tail calls do not save us in Java, rewrite the walk iteratively with cycle detection, look at the stack size options and why they are a stopgap, and finish with how to validate data at import time.
1A Quick Recap of the Call Stack
Each Java thread has its own call stack, a fixed-size block of memory reserved when the thread starts. Every time a method is called, the JVM pushes a frame onto it: a small record holding the method's local variables, its parameters, intermediate values and the address to return to. When the method returns, its frame is popped.
A recursive method that calls itself 40,000 times in a chain needs 40,000 frames alive at once, because none of the calls can return until the deepest one does. The default stack size depends on the platform and JVM settings; on common 64-bit Linux and macOS builds it is 1 MB, and some environments use 512 KB, so check your platform with java -XX:+PrintFlagsFinal -version and look for ThreadStackSize. A simple method's frame takes somewhere around 50 to 150 bytes, so a 1 MB stack typically holds roughly 10,000 to 20,000 such frames. When the next push does not fit, the JVM throws StackOverflowError.
2Reproducing the Failure
Here is the kind of code that fails. It counts categories in a tree by visiting each child recursively.
Notice that the number of categories is not the problem. A tree with a million categories spread over 6 levels needs only 6 or 7 frames at once. What fills the stack is depth: the longest chain from the root to a leaf.
3Why Java Does Not Save Us With Tail Calls
Some languages turn a tail call, a call that is the very last thing a method does, into a jump that reuses the current frame. Then a tail-recursive method runs in constant stack space. Scheme guarantees this, and Scala's compiler rewrites self tail calls into loops when we mark them with @tailrec.
The JVM does not do this. The bytecode has no tail-call instruction, and HotSpot's compilers do not eliminate tail calls, partly because Java's stack traces and some security and debugging features rely on every frame being present. So even if we rewrite our method with an accumulator so that the recursive call is in tail position, each call still pushes a new frame and the same 40,000-level input overflows. Our method is not even tail recursive anyway, because it adds to total after each child returns.
4Fix: Walk the Tree With an Explicit Stack
The reliable fix is to keep the list of pending categories ourselves, in an ArrayDeque on the heap, instead of in call frames on the thread stack. The heap is measured in gigabytes rather than a megabyte, and each pending entry is just one reference in an array.
- Push the root onto the deque
- Deque empty?YesReturn the totalNoPop one category
- Id already visited?YesSkip itNoCount it, mark it visited
- Push its childrenstate lives on the heap, not in frames
- Back to the empty check
5 steps in order. Play them, or step through them one at a time.
Each category is processed once, whatever the depth or cycles.
Notice the visited set. Bad imports do not only create deep chains; they also create cycles, such as category A whose parent is B while B's parent is A. A recursive walk over a cycle never reaches a leaf: with deep data it overflows, and with a cycle it would overflow too, but an iterative walk without a visited set would loop forever and grow the deque until the heap runs out. Checking each id once makes the traversal finish in O(n) time on any input.
5Bigger Stacks Are a Stopgap
Two quick options make the error go away for this customer. We can raise the default stack with a JVM flag such as -Xss8m, or run the walk in a dedicated thread created with a larger stack size.
Both are stopgaps. -Xss applies to every thread the JVM creates, so a service with 500 threads reserves several gigabytes of address space for stacks it rarely uses, and the next import with 400,000 levels fails again. The stack size argument to the Thread constructor is only a request that the JVM may ignore on some platforms. They are fine for buying time during an incident; the iterative rewrite is the fix.
6Follow-up questions
How would you validate the data at import time?
The import should check the shape of the tree before it is saved. We build the parent map from the imported rows, then for each category follow parent pointers up to the root while counting steps, using a visited set: if we see an id twice, the data has a cycle, and if the count passes a business limit, say 20 levels for a product catalogue, the data is suspicious. Either case rejects the import with a clear message naming the offending ids. Adding a depth column maintained by the import, and a database constraint that a category cannot be its own ancestor, keeps bad shapes out even when another tool writes the data.
Can you catch StackOverflowError and carry on?
Technically yes, since it is a Throwable, but it is a poor recovery. It can be thrown in the middle of any method, including library code that was updating shared state, so the program may be left inconsistent. It is better to prevent it with an iterative design and depth limits.
Is the iterative version slower?
Not meaningfully. The deque push and pop are a few nanoseconds each, comparable to a method call, and the HashSet of ids is the main extra cost. For a normal 6-level tree the difference is invisible, and the iterative version keeps working on every input.
7Conclusion
In this answer, we saw that each recursive call uses a stack frame and a thread's stack, often 512 KB to 1 MB, holds only tens of thousands of them, so 40,000 nested categories overflow. The JVM does not eliminate tail calls, so tail-recursive rewriting does not help. The fix is an iterative walk with an ArrayDeque that keeps pending work on the heap and a visited set that stops cycles; larger stacks via -Xss or a Thread constructor are a stopgap; and the import should reject cycles and absurd depths before the data is stored.
Open with
The stack overflow comes from depth, not size: each recursive call pushes a frame, and a thread stack, typically 512 KB to 1 MB depending on the platform, fits maybe ten or twenty thousand frames for a simple method.
Then, if they want more
This customer's data has a chain 40,000 levels deep, so the walk runs out. Java will not rescue a tail-recursive rewrite either, because the JVM does not do tail call elimination; every call still gets its own frame.
So I would rewrite the traversal iteratively with an ArrayDeque as an explicit stack: push the root, pop a node, process it, push its children. That moves the pending work to the heap, where 40,000 references cost almost nothing.
I would add a visited set of ids, because a bad import that creates deep chains can also create cycles, and with a cycle an iterative walk without that set would never finish.
Raising -Xss or starting a thread with a bigger stack is something I would use only as an emergency stopgap, since it costs memory on every thread and the next input can be deeper. Finally I would fix the import: detect cycles and reject trees deeper than a sensible business limit before saving them.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "A method that walks a category tree recursively throws StackOverflowError for one...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/c12bdc48e9/