1
votes

In Java, each thread will have some stack memory allocated to it which is defined by -Xss parameter and there is some default value.

Now, I overridden the default stack size by running below code as java -Xss1k Test.

Last output:

18479
18480Exception in thread "main" java.lang.StackOverflowError

Questions:

  • Why values till 18479 printed? I was expecting far less values because I mentioned stack size of 1KB and was storing an int on each stack frame.
  • With 1KB or 1024 bytes of stack size, only 256 (1024/4) int values could be storable. No? Because with each recursive call one stack frame will be added and int will be stored on it. So, as soon as 256 stack frames with size of 4 bytes each are added there should have been StackOverflowError.
  • My understanding is that the global scoped counter will not contribute in any way to the stack consumption because it will live in old gen space. Confirm?


 public class Test {
    private static int counter = 0;
    public static void main(String[] args) {
        getMeStackOverflowException();
    }

    private static void getMeStackOverflowException(){
        int x = 123;
        System.out.println(Test.counter++);
        getMeStackOverflowException();
    }
}
1

1 Answers

1
votes

With 1KB or 1024 bytes of stack size, only 256 (1024/4) int values could be storable. No?

No. The return address is also stored on the stack, so you should overflow in fewer than 256 recursive calls.

My understanding is that the global scoped x will not contribute in any way to the stack consumption because it will live in old gen space. Confirm?

Confirmed.

For Windows:

Note that on some versions of Windows, the OS may round up thread stack sizes using very coarse granularity. If the requested size is less than the default size by 1K or more, the stack size is rounded up to the default; otherwise, the stack size is rounded up to a multiple of 1 MB

Source.