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.

6
  • 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. Commented Apr 5, 2020 at 4:17
  • 1
    See stackoverflow.com/questions/19402207/… Commented Apr 5, 2020 at 4: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. Commented Apr 5, 2020 at 4:27
  • Stephen C ----- Thanks for reminding me Commented Apr 5, 2020 at 4:59
  • 1
    Also worth reading: Why is the max recursion depth I can reach non-deterministic? Commented Apr 6, 2020 at 10:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, your comment and that link is very useful, its clear to me now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.