Simulate or generate Out of memory error in java (with example)

What is OutOfMemoryError ?

  • The OutOfMemoryError is thrown by  JVM, when JVM does not have enough available memory, to allocate.
  • OutOfMemoryError falls into the error category (Exception class hierarchy) of VirtualMachineError.

Exception class hierarchy

  • We have shown some of exception classes in Fig 1.
Out of memory jvm exception
Fig 1: Exception class hierarchy

The simulation of OutOfMemoryError:

  • We will allocate large chunk of memory, which will exhaust heap memory storage.
  • We will keep on allocating the memory (in below program) and point will reach, when JVM will not have enough memory to allocate, then.
    • OutOfMemoryError will be thrown
  • We will  catch out of memory error (Note: we can not recover from error conditions e.g. OutOfMemoryError, StackOverflowError etc.).
    • We can log the OutOfMemoryError (e.g to generate the statistics etc).

Program to simulate or generate OutOfMemoryError in java.

package org.learn;

public class SimulateOutOfMemoryError {

 public static void main(String[] args) throws Exception {

  int dummyArraySize = 15;
  System.out.println("Max JVM memory: " + Runtime.getRuntime().maxMemory());
  long memoryConsumed = 0;
  try {
   long[] memoryAllocated = null; 
   for (int loop = 0; loop < Integer.MAX_VALUE; loop++) {
    memoryAllocated = new long[dummyArraySize];
    memoryAllocated[0] = 0;
    memoryConsumed += dummyArraySize * Long.SIZE;
    System.out.println("Memory Consumed till now: " + memoryConsumed);
    dummyArraySize *= dummyArraySize * 2;
    Thread.sleep(500);
   }
  } catch (OutOfMemoryError outofMemory) {
   System.out.println("Catching out of memory error");
   //Log the information,so that we can generate the statistics (latter on).
   throw outofMemory;
  }
 }

}

Output of OutOfMemoryError (usage of JVM memory)

Max JVM memory: 926941184
Memory Consumed till now: 960
Memory Consumed till now: 29760
Memory Consumed till now: 25949760
Catching out of memory error
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
 at org.learn.SimulateOutOfMemoryError.main(SimulateOutOfMemoryError.java:13)
Scroll to Top