But this raises two questions:
- Aren't there other ways for a stack overflow to occur, not only through recursion?
- Does the StackOverflowError happen before the JVM actually overflows the stack or after?
It can also occur when we are Allocating size greater than stack's limit (for eg. int x[10000000];
).
Answer to second is
Each thread has its own stack that holds a frame for each method executing on that thread. So the currently executing method is at the top of the stack. A new frame is created and added (pushed) to the top of stack for every method invocation. The frame is removed (popped) when the method returns normally or if an uncaught exception is thrown during the method invocation. The stack is not directly manipulated, except to push and pop frame objects, and therefore the frame objects may be allocated in the Heap and the memory does not need to be contiguous.
So by considering stack in a Thread we can conclude.
A stack can be a dynamic or fixed size. If a thread requires a larger stack than allowed a StackOverflowError
is thrown. If a thread requires a new frame and there isn’t enough memory to allocate it then an OutOfMemoryError
is thrown.
you can get description for JVM here