The OutOfMemoryError is thrown by JVM, when JVM does not have enough available memory, to allocate. OutOfMemoryError falls into the Error category in Exception class hierarchy.
To generate OutOfMemoryError
- We will allocate a large chunk of memory, which will exhaust heap memory storage.
- We will keep on allocating the memory and point will reach, when JVM will not have enough memory to allocate, then OutOfMemoryError will be thrown.
- Once we will catch the OutOfMemory error, we can log the error.
Example
public class OutOfMemoryErrorDemo { 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 throw outofMemory; } } }
Output
Max JVM memory: 119537664 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 OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:9)
Steps to find the root cause of the OOM
Step 1: Generate a heap dump on OutOfMemoryError
Start the application with the VM argument -XX:+HeapDumpOnOutOfMemoryError. This will tell the JVM to produce a heap dump when an OOM occurs
$ java -XX:+HeapDumpOnOutOfMemoryError ...
Step 2: Reproduce the problem
If we cannot reproduce the problem in the development environment, we may have to use the production environment. When we reproduce the problem and the application throws an OOM, it will generate a heap dump file.
Step3: Investigate the issue using the heap dump file
Use VisualVM to read the heap dump file and diagnose the issue. VisualVM is a program located in JDK_HOME/bin/jvisualvm. The heap dump file has all information about the memory usage of the application.