exceptions

java.lang.OutOfMemoryError – How to solve OutOfMemoryError

In this example we will discuss about OutOfMemoryError in Java. This error is thrown by the Java Virtual Machine (JVM) when an object cannot be allocated due to lack of memory space and also, the garbage collector cannot free some space. The OutOfMemoryError objects are created by the JVM when suppression is disabled and/ir the stack trace is not writable.

The OutOfMemoryError extends the VirtualMachineError class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the VirtualMachineError extends the Error class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause, because these errors are abnormal conditions that shall never occur.

Finally, the OutOfMemoryError exists since the 1.0 version of Java.

The Structure of OutOfMemoryError

Constructors

  • OutOfMemoryError()
  • Creates an instance of the OutOfMemoryError class, setting null as its message.

  • OutOfMemoryError(String s)
  • Creates an instance of the OutOfMemoryError class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The OutOfMemoryError in Java

As we have already explained, the OutOfMemoryError indicates that a new object cannot be created, due to lack of available memory space. The following example reproduces this case:

OutOfMemmoryExample.java:

public class OutOfMemoryErrorExample {
	public static void main(String[] args) {
		Long maxMemory = Runtime.getRuntime().maxMemory();
		System.out.println(maxMemory);
		
		int[] matrix = new int[(int) (maxMemory + 1)];
		for(int i = 0; i < matrix.length; ++i)
			matrix[i] = i+1;
	}
}

In this example, we retrieve and print the available free memory inside the Java Virtual Machine (JVM), using the method freeMemory from the Runtime class. Then, we attempt to create a matrix of integers, whose size is bigger than the available free memory and thus, an OutOfMemoryError is thrown.

A sample execution is shown below:

1841823744
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at main.java.OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:8)

The java.lang.OutOfMemoryError: Java heap space error is thrown because we tried to allocate, more than the available, memory space. Each Java application can use only a limited amount of memory. This amount is specified at the startup of the JVM, by the following parameters:

  • -Xms <size>: specifies the minimum Java heap size.
  • -Xmx <size>: specifies the minimum Java heap size.

You can find the default values for many parameters of the JVM, by issuing the following command in a Linux or Mac terminal:

$ java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
     intx CompilerThreadStackSize                   = 0               {pd product}
    uintx ErgoHeapSizeLimit                         = 0               {product}
    uintx HeapSizePerGCThread                       = 87241520        {product}
    uintx InitialHeapSize                          := 130023424       {product}
    uintx LargePageHeapSizeThreshold                = 134217728       {product}
    uintx MaxHeapSize                              := 2071986176      {product}
     intx ThreadStackSize                           = 1024            {pd product}
     intx VMThreadStackSize                         = 1024            {pd product}
java version "1.8.0_11"
Java(TM) SE Runtime Environment (build 1.8.0_11-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.11-b03, mixed mode)

In Windows, you may use the following command:

java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

For a complete list of all the parameters of the JVM, you shall execute the following command:

java -XX:+PrintFlagsFinal -version

More about the OutOfMemoryError in Java

The OutOfMemoryError is thrown due to lack of available memory space. The garbage collector is responsible for detecting objects that are not being used or referenced and collect them. In this way, memory space is being reclaimed for Java applications. However, there are cases where the garbage collector cannot reclaim portions of memory, despite the fact that these objects are no longer accessible by the Java application. These are called memory leaks and can severely limitate the available memory space.

Memory leaks can be created very easily in Java:

MemoryLeakExample.java:

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class MemoryLeakExample {
	public static void main(String[] args) {
		Random random = new Random();
		Map sampleMap = new HashMap();
		
		// Loop forever...
		while(true) {
			// Create and store a random pair.
			int randomValue = random.nextInt();
			sampleMap.put(randomValue, String.valueOf(randomValue));
		}
	}
}

In this example, we create and store random pairs in a HashMap. However, our application only stores values to the HashMap and never retrieves values from it. Thus, memory space is occupied for no reason and the garbage collector cannot reclaim that space, because our application holds a reference to that HashMap. Thus, memory leaks are essential for memory space and must be removed.

Finally, as you can see from here, there are many different causes that can throw an OutOfMemoryError in Java:

  • java.lang.OutOfMemoryError: Java heap space.
  • java.lang.OutOfMemoryError: PermGen space.
  • This error indicates that the permanent generation is full. In Java, the permanent generation is the memory space where class and method objects are stored.

  • java.lang.OutOfMemoryError: Requested array size exceeds VM limit.
  • This error indicates that a Java application attempts ti allocate an array, whose size is larger than the heap size. For example:

    	public class OutOfMemoryErrorVMLimitExample {
    		public static void main(String[] args) {
    			int[] matrix = new int[Integer.MAX_VALUE];
    		
    			for(int i = 0; i < matrix.length; ++i)
    				matrix[i] = i+1;
    		}
    	}
    	

    A sample execution is shown below:

    	Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    		at main.java.OutOfMemoryErrorVMLimitExample.main(OutOfMemoryErrorVMLimitExample.java:5)
    	
  • java.lang.OutOfMemoryError: request <size> bytes for <reason>. Out of swap space?
  • This error indicates that an allocation from the native heap space has failed and also, the heap space is close to exhaustion. Moreover, the message of the error indicates the number of bytes that failed and the reason for the memory request.

  • java.lang.OutOfMemoryError: <reason> <stack trace> (Native method).
  • This error indicates that the allocation failure was detected in a JNI or native method instead of the JVM code.

How to deal with the OutOfMemoryError

  • The most obvious solution to this error is to increase the available memory size for the Java Virtual Machine. If your application requires more memory then, you shall grant it to your application.
  • Verify that your application does not store unnecessary information. Store and maintain only those pieces of information required for the proper execution of your Java application.
  • You can use the availabe memory analyzer tools, in order to carefully observe the portions of memory occupied by your application. Examples of such tools are the Eclipse Memory Analyzer and Java Heap Analysis Tool (jhat).

Download the Eclipse Project

This was a tutorial about OutOfMemoryError in Java.

Download
You can download the full source code of this example here: OutOfMemoryErrorExamples.zip.

Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Debatosh Bose
Debatosh Bose
5 years ago

it’s wrong. java.lang.OutOfMemoryError is an error, not an exception. You have to use OutOfMemoryError and some memory realize code.

Back to top button