Java Heap Memory Error

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to use Java Heap Memory effectively to avoid Java Heap Memory error.

Java Heap Memory Error

Java Heap Memory Error occurs when the Java Virtual Machine (JVM) runs out of memory while allocating objects to Java Heap Memory. Poor programming practices, memory leaks, third-party libraries can all result in this error.

Code:

import java.util.ArrayList;

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

To see the error in action, compile and run the code in the terminal:

javac JavaHeapMemoryError.java
java -Xmx512m JavaHeapMemoryError

The program tries to allocate as much memory as possible by continuously creating objects and adding them to the ArrayList until the JVM throws the OutOfMemoryError. The -Xmx parameter sets the maximum heap memory allocated to the JVM.

Causes of Java Heap Memory Error

Java Heap Memory Error occurs primarily due to poor programming practices, memory leakage, and third-party libraries. To prevent it, we must avoid infinite loops, unused objects held for too long without being cleaned up, and make unused objects available to the garbage collector.

Code:

public class JavaHeapMemoryError {
    public static void main(String[] args) {
        int[] arr = new int[100000000];
        for(int i=0; i<arr.length; i++){
            arr[i] = i;
        }
        System.out.println("Memory allocated");
    }
}

To see the code in action, compile and run the code in the terminal:

javac JavaHeapMemoryError.java
java -Xmx256m JavaHeapMemoryError

Memory Leak

Memory Leak occurs when an unused object in heap memory still has valid references and cannot be removed by the Garbage Collector. To avoid memory leaks, all open resources must be closed using the finally block.

Code:

public class MemoryLeak {
    static ArrayList<String> arrList = new ArrayList<String>(500);
    public static void main(String args[]) {
        for (int i = 0; i < 500; i++) {
            arrList.add("Element " + i);
        }
        arrList = null;
    }
}

To see the code in action, compile and run the code in the terminal:

javac MemoryLeak.java
java -Xmx256m MemoryLeak

Excessive use of finalizers

Excessive use of finalizers can lead to Java Heap Memory Error because classes that contain a finalize method do not have their object spaces reclaimed during Garbage Collection.

Code:

public class ExcessiveFinalizer {
    public void finalize() {
        //Do some cleanup
    }

    public static void main(String[] args) {
        ArrayList<ExcessiveFinalizer> list = new ArrayList<ExcessiveFinalizer>();
        while (true) {
            list.add(new ExcessiveFinalizer());
        }
    }
}

To see the code in action, compile and run the code in the terminal:

javac ExcessiveFinalizer.java
java -Xmx256m ExcessiveFinalizer

Increase Heap Memory

If the error was caused by insufficient memory allocated to JVM, we can increase the heap space available to it by increasing the limit set by -Xmx command.

Code:

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

To see the code in action, compile and run the code in the terminal:

javac IncreaseHeapMemory.java
java -Xmx8g IncreaseHeapMemory

Summary

In this lab, you have learned how to manage Heap Memory effectively for your Java applications to avoid Java Heap Memory Errors. We explored different techniques to prevent the error, such as avoiding inefficient loops, closing unused resources, and making unused objects available to the garbage collector early. Finally, if insufficient heap memory was the cause of the error, we increased the limit using the -Xmx command.

Other Java Tutorials you may like