Java.lang.outofmemoryerror: java heap space

The name of the error itself conveys that it is an out-of-memory error where the JVM throws such error when it cannot allocate an object in the heap memory. So, in this section, we are going to discuss the Java.lang.outofmemory error, about heap space, and how to fix the error.

What is Heap Space in Java

In Java programming language , a user creates an object, and that object gets stored in the heap area of the Java. It is the Java restriction that a Java application can only use a limited amount of memory. The JVM architecture is composed of essential tools and libraries, and the space area is divided into two different parts, i.e., Heap space and Permgen (also known as Permanent Generation) . Thus when a JVM is launched, the size of the Heap space and permgen is set.

What is Java.lang.outofmemoy error

An error is thrown by the Java Virtual Machine when it finds that not enough memory is left for storing the object in the heap space, and as a result, the JVM throws an error that it is unable to allocate the object because no more space is left for storing it. In Java programming language, the OutOfMemoryError is thrown means that:

  • The user is doing something wrong, which means the user tries processing high data or holding onto objects for a long time.
  • Such a memory error also means that a problem has occurred that the user cannot handle, such as a third-party library that caches strings or an application server that doesn't clean up after deploys.
  • It may sometimes also means that such error has nothing to do with objects on the heap. It can also be thrown by native library code when a native allocation cannot be satisfied, such as if swap space is low.
  • Program creating outofmemory error

    Below is the program code:

    public class outmem { public static void main(String[] args) throws Exception { int arrSize = 15; System.out.println("Maximum memory " + Runtime.getRuntime().maxMemory()); long memoryConsumed = 0; try { long[] memoryAllocated = null; for (int loop = 0; loop < Integer.MAX_VALUE; loop++) { memoryAllocated = new long[arrSize]; memoryAllocated[0] = 0; memoryConsumed += arrSize * Long.SIZE; System.out.println("Memory Consumed: " + memoryConsumed); arrSize *= arrSize * 2; Thread.sleep(500); } catch (OutOfMemoryError outofMemory) { System.out.println("Catching out of memory error"); throw outofMemory;

    Program Snippet:

    Output:

    What causes Java.lang.outofmemory error

    There are the following reasons because of which the JVM throws outofmemory error:

  • Poor Programming Approach: The occurrence of such error may mean that object could not be allocated in the Java heap. Not mandatory that this error implies a memory leak always. Also, it can be because of the configuration issue as well, where it is that for the application, the specified heap size or the default heap size is insufficient. In other cases, and for a long-lived application, the error might indicate that the application unintentionally holds references to objects, thus preventing the objects from being garbage collected. Thus it is the equivalent of a memory leak. It is because the APIs (Application Programming Interface) invoked by an application could also be unintentionally holding object references.
  • Data Usage: Almost every Java application is designed to tackle a certain amount of users for a particular duration. In case the number of users (limit of users) is crossed, and the threshold value becomes more than the expected value, the operation terminates, and the error java.lang.outofmemory error is thrown out.
  • Leakage in memory: Because of using a poor programming approach, it could lead to the consumption of a high amount of memory which, as a result, leaves out some or the other objects in the Java heap space. The leaked objects consume almost all the memory in the JVM, and thus no more memory is left for other objects to get stored. As a result, JVM throws Java.lang.outofmemory error.
  • Low memory: It is also a cause of the Java.lang.outofmemory error because if a system has less memory for the JVM to execute the code, we can increase the size of the system to make up the memory. Thus, if the JVM does not find enough memory for executing the code and store the objects, it triggers out Java.lang.outofmemory error indicating that no space is left for allocating a new object.
  • Excessive use of finalizers: If in an application, a class is having a finalize method, then objects of such type are not able to obtain their space at the time of Garbage Collection (GC), and after Garbage Collection, these objects are kept in a queue for finalization later. In Java, finalizers are executed via a daemon thread that is used for servicing the finalization queue. If it is found that the finalizer thread is not coping with the finalization queue, the heap space could be filled completely, and the error java.lang.outofmemory error would be thrown.
  • Fixing Java.lang.outofmemory Error in Java

    Once we got to know the causes because such an error has occurred, so just need to fix this error, and as the error gets resolved, JVM will store the objects successfully in the Java heap space. To fix the error, particular solutions could be taken up due to the causing Java.lang.outofmemory error:

    Solution 1: The easiest solution to remove such error is to increase the memory size of the JVM heap space. To increase the size of the heap space, use "-Xmx" java options to solve the out-of-memory error. This configuration will provide 1024 heap space to the application. However, increasing the heap size will not cover all the necessary errors (such as memory leaks) for your application that is running on the JVM. Also, increment in the heap space would also increase the length of the GC pauses that affect the application's latency or throughput. It is one solution but is not the all-time solution. To increase heap size:

  • Open the eclipse.ini file of your Eclipse IDE as shown below:
  • Now change the Xmx value as per your system requirement as shown below:
  • Relaunch the Eclipse IDE, and the heap size will be increased.
  • To resolve out the error properly, one needs to detect that part of the code that is causing such error.

    Solution 2: Instead of trying to increase the heap size of the JVM and still facing the error, one should look for the memory leakage if any is occurring. To examine the memory leakage in Eclipse, make use of the Eclipse Memory Analyzer (known as MAT that is used to find memory leaks and reduce memory consumption) or any other tool through which one can analyze the heap dump. Although finding memory leakage is a typical task, it is one of the good approaches that can be used.

    Tools for Detecting and fixing the error

    The error java.lang.outofmemory error needs to be fixed by identifying those objects which are taking up memory, and the amount of memory such objects are exhausting. It is important to know, and for this, we need to use some of the available Java tools that would make it possible to identify. Possibly, there are the following tools through which we can analyze the heap and know the problem:

  • MAT (Eclipse Memory Analyzer): It is an Eclipse foundation that is used for analyzing the Java heap dump. The tool is used for finding the memory leaks as well as classloader leaks in the code. It also helps in minimizing memory consumption. The MAT tool can be used to analyze heap dump containing millions of objects and also helps in detecting the culprit for memory leakage. The user can download the MAT analyzer from the official website of Eclipse https://www.eclipse.org/mat/downloads.php and set it to the Eclipse IDE. The snapshot for the MAT tool is shown below:
  • Visualgc: The acronym for Visualgc is Visual Garbage Collection Monitoring Tool that can be attached to the instrumented hotspot JVM. The main objective of Visualgc is to represent all the key data in a graphical manner, including class loader, JVM compiler performance data, and Garbage Collection. Also, the target JVM is identified by its virtual machine identifier that is also known by the name VMID. To download Visualgc to the system, download jvmstat first, and it will carry Visualgc with it. The link to download jvmstat is: https://www.oracle.com/java/technologies/jvmstat.html
    A snapshot to download jvmstat is:

    So, in this way, the Java.lang.out of memory: java heap space error will be identified and can be solved out by following these specified options.

    Next Topic Banker's Algorithm Java
  •