When you create an object with new
, it invokes the object's constructor. The constructor is a method. Each method invocation results in the creation of another stack frame, each of which is using a portion of your available stack space. Once you run out of stack space, you will get a StackOverflowError
. An unlimited recursion will quickly exhaust the available stack space. With your code, there is a race between which will exhaust first, stack space or heap space; however, with most default limits, the stack is going to be much smaller than the heap.
To cause an OutOfMemoryError
create lots of objects inside a while(true)
loop, and ensure that the objects aren't collectible by the garbage collector. For example:
public class MyObject {
int[] array = new int[1024*256];
static List<MyObject> myList = new LinkedList<>();
public static void main(String[] args) throws Exception {
while(true){
myList.add(new MyObject());
}
}
}