Reputation: 1177
package com.atul;
public class StackOverFlow {
public StackOverFlow() {
callStackOverFlow();
}
public void callStackOverFlow() {
StackOverFlow st = new StackOverFlow();
}
public static void main(String[] args) {
StackOverFlow st2 = new StackOverFlow();
}
}
In above program I was trying to get OutOfMemory error but I get StackOverFlow error. As per my knowledge all the objects are created in the Heap. Here we are doing recursion with constructor, still I get the StackOverFlow error.
Why?
Upvotes: 1
Views: 79
Reputation: 533550
You run out of stack (which has a maximum depth around 10,000 for simple cases) long before you run out of heap memory. This is because every thread has its own stack so it must be a lot smaller than the shared heap.
If you want to run out of memory, you need to use up the heap faster.
public class OutOfMemoryMain {
byte[] bytes = new byte[100*1024*1024];
OutOfMemoryMain main = new OutOfMemoryMain();
public static void main(String... args) {
new OutOfMemoryMain();
}
}
Upvotes: 7
Reputation: 14363
Before the memory get full of objects and program aborts due to out of memory; you ran out of stack which stores the method call and hence you are getting Stackoverflow Error.
Overflow error would come when your objects would fill up the heap space...
Upvotes: 0
Reputation: 272307
The stack size in the JVM is limited (per-thread) and configurable via -Xss
.
If you want to generate an OOM, I would suggest looping infinitely and instantiating a new object per loop, and storing it in a collection (otherwise the garbage collection will destory each instance)
Upvotes: 1