Phase 6 of 20 · Topic 6.5

Recursion & StackOverflowError Call Stack Safety

1Concept

Recursion occurs when a method invokes itself. Each call pushes a new Stack Frame containing local variables and return addresses onto the thread's call stack. Without an unambiguous base termination condition, the thread stack exhausts `-Xss` memory limit, throwing `java.lang.StackOverflowError`.

2Architecture Diagram

Call Stack (Thread Stack - Default 1MB):
  +--------------------------------+
  | computeFactorial(1) -> returns 1
  +--------------------------------+
  | computeFactorial(2) -> waits...
  +--------------------------------+
  | computeFactorial(3) -> waits...
  +--------------------------------+
  | main() Frame                   |
  +--------------------------------+

3Code Example

Core Java
public class RecursionSafetyDemo {
    public static long safeFactorial(int n) {
        // Base condition guarantees stack termination
        if (n <= 1) return 1;
        return n * safeFactorial(n - 1);
    }

    public static void main(String[] args) {
        int num = 5;
        long fact = safeFactorial(num);
        System.out.println("Safe Factorial of " + num + ": " + fact);
        System.out.println("Stack Frame cleared and execution returned to main.");
    }
}

4Expected Output

Safe Factorial of 5: 120
Stack Frame cleared and execution returned to main.

5Key Takeaways

  • Java HotSpot does NOT optimize tail-recursion into loops; deep recursion will exhaust the call stack.
  • StackOverflowError is an Error (not Exception); catching it is generally an anti-pattern.
  • Replace deep recursive algorithms with iterative loops or an explicit Heap-based Stack data structure.