0

I know that object references are created on the stack, and the objects themselves are created on the heap. In the code below, I try to fill the heap by creating a large number of Main objects, using recursion in the constructor; However, instead of an OutOfMemoryError, I get a StackOverflowError

public class Main {
 public Main() {
     new Main();
}

public static void main(String[] args) {
    new Main();
}
}

Why does this happen?

code
  • 23
  • 7
  • Possible duplicate of [What is a StackOverflowError?](https://stackoverflow.com/questions/214741/what-is-a-stackoverflowerror) – Samuel Philipp Apr 03 '19 at 19:01

1 Answers1

0

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());
        }
    }
}
Dominik Wosiński
  • 3,769
  • 1
  • 8
  • 22