Monday, 16 May 2022

Quick guide to OutOfMemoryError in Java

OutOfMemoryError thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

 

 


OutOfMemoryError is related to Java Heapmemory. It typically occur, when the application request memory for a new object, but the heap is already full.

 

Stack vs Heap memory

Stack is a special region in computer memory, that stores temporary variables like local variables, parameters, function calls etc., Stack works in last in first out (LIFO) order. Whenever a new local variable initialized inside a function, it is pushed onto the stack, when the function finished execution, all the local variables pushed by that function onto the stack are removed from the stack. Read this post for more details.

 

Heap is a portion of memory where dynamic allocation and de allocations happen. When the application request for a new object, JVM allocates the memory in Heap. Heap memory is slightly slower to read from and written to, because pointer access is needed to access heap memory. The JVM allocates Java heap memory from the OS and then manages the heap for the Java application. Refer this post for more details.

 

Let’s write a simple program to produce OutOfMemoryError.

 

OutOfMemoryErrorDemo.java

public class OutOfMemoryErrorDemo {

	public static void main(String[] args) {
		Integer obj[] = new Integer[Integer.MAX_VALUE];

		for (int i = 0; i < Integer.MAX_VALUE; i++)
			obj[i] = i;

		System.out.println("I am done");
	}

}

 

Compile and run the above program.

$javac OutOfMemoryErrorDemo.java 
$
$java OutOfMemoryErrorDemo
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
	at OutOfMemoryErrorDemo.main(OutOfMemoryErrorDemo.java:4)

 

How to address the OutOfMemoryError?

a. First Profile your application and try to figure out, is your application referring any unused objects, or is there any memory leaks etc., You can refer this post to find the tools to analyze your java application.

 

b. Increase the heap size. Refer this post for more details.

  

References

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

 

You may like

Interview Questions

How to get the name of calling class that invoke given method?

Implement map using array as storage

How to resolve NoClassDefFoundError?

Jagged arrays in Java

Get the length of longest row in a two dimensional jagged array in Java

No comments:

Post a Comment