Search code examples
javajvmstack-overflow

About Java VM Stack Overflow


Thanks!

I'm learning JVM, and test VM stack overflow, found a strange phenomenon. I call a method recursively in two ways, but I was confused with result.

VM Options: -Xss108k -Xms10m -Xmx10m

public class T2 {
    private int stackLength = 1;
    public void stackLeak(){
        long[] a = new long[2000]; //define this array or not
        stackLength++;
        stackLeak();
    }

    public static void main(String[] args) {
        T2 oom = new T2();
        try{ //
            oom.stackLeak();
        } catch(Throwable e){
            System.out.println("stack length: " + oom.stackLength);
            e.printStackTrace();
        } finally{

        }
    }


}

I have re-run many times, results almost the same. I thought, array saved in heap, it won't affect VM stack, but it did.


Solution

  • Array allocation affects execution time of the program. The longer the program runs, the more are the chances that JIT compiler will kick in, and the program will continue execution in compiled mode.

    The difference in the stack depth is explain by the background JIT compilation. See this answer for details.

    To make the fair comparison, run JVM with JIT compilation turned off: -Xint. In this case, array allocation will make the maximum recursion depth expectedly smaller (since there will one more stack slot used for an array reference).