Tuesday, April 23, 2024

Difference Between StackOverflowError and OutOfMemoryError in Java

Differences between StackOverflowError and OutOfMemoryError in Java is a frequently asked Java interview question. You may also encounter one of these errors in your application. Before going into StackOverflowError Vs OutOfMemoryError let’s get some background about these errors.


StackOverflowError in Java

Whenever you run any Java program even if you don’t explicitly create any thread a main thread is started and that thread runs the program.

For each thread JVM creates a stack, whenever any method is invoked a new frame is created and pushed into the JVM stack for the thread. Each frame stores data corresponding to the invoked method including local variables, operand stack and a reference to the run-time constant pool and reference to exception table.

Once the method execution is completed corresponding stack frame is popped out of the stack.

JVM throws StackOverflowError if the stack memory requirement of any method exceeds the permitted stack memory size. A very common scenario where you may see StackOverflowError is when you have a recursive method with no terminating condition. For example following program that calculates factorial of a number using recursive method call. Since there is no exit condition defined so recursive method call never ends resulting in StackOverflowError.

public class StackOFErrorExp {
  public static void main(String[] args) {
    double factorialResult = factorial(1000);
    System.out.println(factorialResult);
  }
  private static int factorial(int i) {
    /*
     * if (i == 0 || i == 1 ) '
     *  return 1;
     */
    return i * factorial(i - 1);
  }
}

OutOfMemoryError in Java

In Java, memory for each object, for arrays and for instance variables (variables at class level not method level) is created on the heap. When there are no references to an object that object is garbage collected thus clearing the heap memory.

If you try to create an object or array that tries to take more memory than the allocated heap memory or there are a lot of objects in heap that are still referenced so can’t be garbage collected and JVM tries to allocate heap memory for a new object JVM throws java.lang.OutOfMemoryError because there is no sufficient heap memory.

Here is an example of java.lang.OutOfMemoryError where objects are added to an ArrayList in an infinite loop. Since objects stored to the List are not garbage collected so heap memoery will finally run out of memory resulting in OutOfMemoryError.

public class OutofMemoryExp {
  public static void main(String[] args) {
    List list = new ArrayList<>();
    int i = 0;
    // results in indefinite loop
    while(true) {
      i++;
      list.add(i * 1000000);
    }  
  }
}

Output

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at java.base/java.util.Arrays.copyOf(Arrays.java:3721)
 at java.base/java.util.Arrays.copyOf(Arrays.java:3690)
 at java.base/java.util.ArrayList.grow(ArrayList.java:237)
 at java.base/java.util.ArrayList.grow(ArrayList.java:242)
 at java.base/java.util.ArrayList.add(ArrayList.java:485)
 at java.base/java.util.ArrayList.add(ArrayList.java:498)
 at org.netjs.examples.OutofMemoryExp.main(OutofMemoryExp.java:14)

StackOverflowError Vs OutOfMemoryError in Java

  1. StackOverflowError is thrown when there is no sufficient stack space for storing method data.
    OutOfMemoryError is thrown when no sufficient heap space left for creating new objects or requested array size is more than heap memory.
  2. StackOverflowError happens when you have Recursive methods with out terminating condition.
    OutOfMemoryError happens when new objects can’t be allocated on the heap as existing objects still have references so can’t be garbage collected.
  3. In order to avoid StackOverflowError ensure that methods are finishing their execution and corresponding stack memory is freed.
    In order to avoid OutOfMemoryError ensure that there are no references to objects which you don’t need anymore so that such objects can be garbage collected freeing heap memory in the process.

That's all for this topic Difference Between StackOverflowError and OutOfMemoryError in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between Checked And Unchecked Exceptions in Java
  2. Difference Between throw And throws in Java
  3. final Vs finally Vs finalize in Java
  4. java.lang.ClassCastException - Resolving ClassCastException in Java
  5. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java

You may also like-

  1. Java Exception Handling Interview Questions And Answers
  2. Array in Java With Examples
  3. Varargs (Variable-length Arguments) in Java
  4. Type Erasure in Java Generics
  5. Pre-defined Functional Interfaces in Java
  6. Linear Search (Sequential Search) Java Program
  7. Introduction to Node.js
  8. Bean Scopes in Spring With Examples

3 comments:

  1. Excellent java tutorial..please provide some stuffs how to prevent singleton pattern from reflection,serialisation and cloning

    ReplyDelete
  2. Thanks for a clear explanation. Not sure author reading comments to the old topics, but you have a little typo:

    there are nto references to objects // nto -> no

    ReplyDelete