Site icon

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

What is OutOfMemoryError ?

Exception class hierarchy

Fig 1: Exception class hierarchy

The simulation of OutOfMemoryError:

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)
Exit mobile version