Why java recursively calling function can run forever even though StackOverflowError?

Viewed 72

I met the following problem in a Java exam, why following recursively calling a function can run forever even though StackOverflowError?

public class Solution {
    static int i = 0;

    public static void f(){
        System.out.println(i++);
        try {
            f();
        } catch (StackOverflowError e) {
            System.out.println(e);
            f();
        }
    }

    public static void main(String[] args) {
        f();
    }
}

I cannot understand why JVM can still run when I've exhausted all call stack memory? Is there any reference, like JVM specification or JVM source code, can explain above phenomenon?

1 Answers

I'm neither java nor jvm expert, but I think adding a extra recursive depth output can show exactly what is going on with the call stack.

public class Solution {
  static int i = 0;

  public static void f(int depth) {
    System.out.println(i++);
    System.out.println(String.format("depth=%d", ++depth));
    try {
      f(depth);
    } catch (StackOverflowError e) {
      System.out.println(e);
      f(depth);
    }
  }

  public static void main(String[] args) {
    f(1);
  }
}

In my test, typical output is

...more
java.lang.StackOverflowError
161735
depth=3745
161736
depth=3746
161737
java.lang.StackOverflowError
161738
java.lang.StackOverflowError
161739
java.lang.StackOverflowError
161740
depth=3744
161741
depth=3745
...more

StackOverflowError is thrown because jvm is considering a size limit(1M by default?) of stack memory has reached, but the exception is caught, so the recursion is not stopped, it still tries to call, jvm throw away the recent 1 or 2 problematic calls, and then try continue, so the depth value goes around the same maximum value again and again.

I think this way the OP can understand why i is increasing without any problem. I've exhaust the call stack memory -- you haven't, you nearly exhaust, but jvm always cleared latest few calls to avoid exhaust.

Related