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
counterwill 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();
}
}