Call Stack and StackOverflowError
Every method call allocates a frame on the call stack. Deep recursion can lead to a StackOverflowError when the depth exceeds the stack size.
Tail recursion is not automatically optimized to a loop in Java. Preferably process deep structures iteratively or with an explicit stack if the depth is large.
Example: Recursion depth n in a linear chain of calls fact(n) -> fact(n-1) -> ...
$$\textit{frames} \propto \textit{depth}$$
Where used
Deep XML/JSON documents, symmetric recursion over long lists, naive tree depth without balance. Monitoring and hardening: Recursion limits in parsers, iterative alternatives in hot paths, explicit own stacks if the logic should remain recursive.
Depth
Every active method call has an activation record with local variables, return information, and management data. Recursive calls generate separate records even though they are executing the same method code.
The JVM additionally uses metadata such as stack maps, allowing verification and garbage collection to reliably recognize references at specific points in the program. Therefore, the actual memory requirements per call depend not only on visible local variables.
A StackOverflowError occurs when the required call depth exceeds the available thread space. A larger limit merely shifts the problem. For input-dependent deep traversals, an explicit working structure is often more controllable.
Difficulty levels
- Draw activation records from a short recursion.
- Separate call depth from the total number of executed calls.
- Convert a deep traversal to an explicit state.
Pitfalls
The error does not necessarily prove an infinite loop. Even terminating recursion can become too deep for large inputs, and caught memory shortages do not automatically make the state safely resumable.
Tasks
Card Info
- Topic: Algorithms and Data Structures
- Difficulty: Beginner
- Completed: 0 users