Signup/Sign In

Java Heap Memory Error

Errors and exceptions are very common when working with any programming language. In Java, all objects are stored in the Heap memory, and JVM throws an OutOfMemoryError when it is unable to allocate space to an object. Sometimes this error is also called Java Heap Space Error. Let's learn more about this error.

Java OutOfMemory Error

Reasons Behind the java.lang.OutOfMemoryError

Java has a predefined maximum amount of memory that an application should take and if the application exceeds this limit then the OutOfMemory error is thrown. Let's take a look at the reasons behind this error.

  1. This error can occur due to poor programming practices like using inefficient algorithms, wrong data structure choices, infinite loops, not clearing unwanted resources, holding objects for too long, etc. If this is the reason behind the error then one should reconsider the choices made when writing the program.
  2. There can be some other reasons that are not in control of the user. For example, a third-party library that is caching strings, or a server that does not clean up after deploying. Sometimes this error can occur even if everything is fine with the heap and the objects.
  3. Memory Leaks can also lead to OutOfMemory errors. A memory leak is a situation when an unused object is present in the heap and cannot be removed by the Garbage Collector because it still has valid references to it. Open resources can also lead to memory leaks and they must be closed by using the finally block. The garbage collector will automatically remove all the unreferenced objects and this situation can easily be avoided by making unused objects available to the garbage collector. Additional tools are also available to detect and avoid memory leaks.
  4. Excessive use of finalizers can also lead to the OutOfMemoryError. Classes having a finalize method do not have their object spaces reclaimed at the time of Garbage Collection. After the garbage collection process, these objects are queued for finalization at a later time and if the finalizer thread cannot keep up with the queue then this error is thrown.

We can always increase the memory needed by JVM but if the issue is more advanced then we will eventually run out of memory. One should try to optimize the code and look for memory leaks that may cause this error.

Example: OutOfMemoryError Due to an Infinite Loop

Let's create an ArrayList of Object type and add elements to it infinitely until we run out of memory.

import java.util.ArrayList;
public class OutOfMemory
{
	public static void main(String args[])
	{
		ArrayList<Object> list = new ArrayList<Object>();
		
		while(true)
		{
			Object o = new Object();
			list.add(o);
		}
	}
}

In this example, we will eventually run out of space even if we increase the memory assigned to the application. The following image shows the error message returned by the above program.

OutOfMemory Error

Example: Out of Memory Because of Limited Memory

If the memory assigned to the application is less than the required memory then the OutOfMemory error is returned. We can also try to optimize our code so that its space complexity can be reduced. If we are sure that this error can be fixed if we had more memory then we can increase it by using the -Xmx command. Let's run a program that does not have the required memory.

public class OutOfMemoryError
{
	public static void main(String[] args)
	{
		Integer[] outOfMemoryArray = new Integer[Integer.MAX_VALUE];
	}
}

The error message is shown in the image below.

OutOfMemory Error

Resolving OutOfMemoryError by Increasing Heap Space

Increasing the heap space can sometimes resolve the OutOfMemory error. If we are sure that there are no memory leaks and our code cannot be optimized further, then increasing the heap space could solve our problem. We will use the -Xmx command while running the java application to increase the heap space.

For example, the following code will not work if set a 4MB limit on the memory.

public class OutOfMemory
{
	public static void main(String[] args)
	{
		String[] str = new String[1000000];
		System.out.print("Memory Allocated");
	}
}

OutOfMemoryError because insufficient memory was allocated to the application

However, if we increase the limit to 8MB or anything greater then it works perfectly fine.

Application runs if we allocate 8MB or more space.

Frequently Asked Questions

Q. What is the default heap size in Java?

The default heap size in Java is 1GB and it is sufficient for most tasks.

Q. What is the difference between -Xmx and -Xms?

Xms defines the initial or the minimum heap size and xmx is used to set the maximum heap size. JVM will start the memory defined by -xms and will not exceed the limit set by -xmx.

Q. What is the Stack Memory?

The stack memory is a Last-In-First-Out memory used for static memory allocation and for thread execution. Whenever a new object is created, it is stored in the Heap memory and a reference to it is stored in the stack memory.

Summary

The OutOfMemoryError is a subclass of the VirtualMachineError and it is thrown when JVM does not have sufficient space to allocate new objects. This error can occur due to poor programming practices like using infinite loops or not clearing unwanted objects. This can also occur due to the presence of some third-party libraries. Memory leaks also lead to this error and we can use tools like Eclipse Memory Analyzer to fix them. Sometimes, just increasing the heap space allotted to the application solves the problem. We should also try to look for optimized algorithms so that the overall space complexity of our program is less than the maximum space available.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.