1

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.

  • 2
    Do not post your code and results as screenshots. 1) Many people cannot read screenshots!! (Due to disability, censorship, etc) 2) Screenshots are liable to be deleted, making questions meaningless. 3) We can't copy and paste from a screenshot. EDIT your question and copy-and-paste the code and results into your Question. – Stephen C Apr 05 '20 at 04:17
  • 1
    See https://stackoverflow.com/questions/19402207/java-variable-placed-on-stack-or-heap – Ori Marko Apr 05 '20 at 04:18
  • 1
    Yup. That Q&A explains it. While the array is on the heap, the variable containing the reference to the array is on the stack. But even if there were NO variables, you would still get a stack overflow because there are stack frame overheads. The frame has to hold 1) the pointer to the previous stack frame, and 2) a return address for the current method call. – Stephen C Apr 05 '20 at 04:27
  • Stephen C ----- Thanks for reminding me – Zhang Xujie Apr 05 '20 at 04:59
  • Stephen C ----- Thanks for your help, yes, I know stack frames will lead to StackOverflow, but I confused that why it can creat more stack frames after I defined a array in method. because I think I defined array will make every stack frame more large, in other words, numbers of stack frames should be less than before(not define array) – Zhang Xujie Apr 05 '20 at 05:10
  • 1
    Also worth reading: [“*Why is the max recursion depth I can reach non-deterministic?*”](https://stackoverflow.com/q/27043922/2711488) – Holger Apr 06 '20 at 10:26

1 Answers1

1

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).

apangin
  • 92,924
  • 10
  • 193
  • 247