Heapoverflow instead of Stackoverflow in infinite loop

In java when a method calls itself and results in an infinite loop a stackoverflow error is thrown. While objects are initialized in heap memory shouldn't the heap memory overflow error be thrown since an object is involved to call the method.? Is there any such thing as a heapoverflow error?!

Upvotes: 1

Views: 343

Answers (3)

AtlasMeh-ed
AtlasMeh-ed

Reputation: 477

You're on the right track. You can run out of heap memory but it's not called HeapOverflow. It's called OutOfMemoryError. Although HeapOverflow sounds catchy it's not called that because the heap often has free and allocated areas scattered through out. The stack on the other hand has just two areas, free and allocated. The allocated area grows into the free area as you make more allocations on the stack. Hence you eventually overflow the stack. More on stack vs heap here.

Here is an example of running out of heap memory:

public class RunOutOfMemory {
    public static void main(String[] args){
        System.out.println("Haven't tried to allocate lots of heap memory.");
        int[][] matrix = new int[100000][100000000];
        System.out.println("A miracle occured.");
    }
}

Spoiler alert: you need about 4 terabytes of memory for the miracle to occur

Upvotes: 2

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

If you make

  • your stack size big enough, and/or
  • your heap size small enough,

you will get a heap overflow error (java.lang.OutOfMemoryError) instead of a stack overflow error (java.lang.StackOverflowError).

The reason that you normally don't see this behavior is because, by default (depends on the JVM), stack sizes are a lot smaller than heap sizes, so the stack runs out first.

You can try it out by creating a recursive method and playing around with different heap and stack sizes. The following, for example, will execute MyClass with a heap size of 2MB and a stack size of 4MB. If invoking MyClass executes an infinite recursive method that involves object creation, you're bound to run into an OutOfMemoryError before you run into a StackOverflowError.

java -Xms2m -Xmx2m -Xss4m MyClass

Upvotes: 4

Eric J.
Eric J.

Reputation: 150108

If Java runs out of heap space when trying to allocate an object, you will get an OutOfMemoryError

http://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html

While objects are initialized in heap memory shouldn't the heap memory overflow error be thrown since an object is involved to call the method.?

If you have an infinitely recursive function that also allocates an object from the heap, it is possible to get an OutOfMemoryError first. That depends on the size of the object allocation, and the sizes of the heap and stack.

Upvotes: 0

Related Questions