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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/SystemandDataProcessingGroup -.-> java/xml_dom4j("`XML/Dom4j`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/booleans("`Booleans`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/BasicSyntaxGroup -.-> java/while_loop("`While Loop`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117690{{"`Java Heap Memory Error`"}} java/generics -.-> lab-117690{{"`Java Heap Memory Error`"}} java/xml_dom4j -.-> lab-117690{{"`Java Heap Memory Error`"}} java/arraylist -.-> lab-117690{{"`Java Heap Memory Error`"}} java/classes_objects -.-> lab-117690{{"`Java Heap Memory Error`"}} java/class_methods -.-> lab-117690{{"`Java Heap Memory Error`"}} java/modifiers -.-> lab-117690{{"`Java Heap Memory Error`"}} java/oop -.-> lab-117690{{"`Java Heap Memory Error`"}} java/packages_api -.-> lab-117690{{"`Java Heap Memory Error`"}} java/wrapper_classes -.-> lab-117690{{"`Java Heap Memory Error`"}} java/identifier -.-> lab-117690{{"`Java Heap Memory Error`"}} java/arrays -.-> lab-117690{{"`Java Heap Memory Error`"}} java/booleans -.-> lab-117690{{"`Java Heap Memory Error`"}} java/comments -.-> lab-117690{{"`Java Heap Memory Error`"}} java/data_types -.-> lab-117690{{"`Java Heap Memory Error`"}} java/for_loop -.-> lab-117690{{"`Java Heap Memory Error`"}} java/operators -.-> lab-117690{{"`Java Heap Memory Error`"}} java/output -.-> lab-117690{{"`Java Heap Memory Error`"}} java/strings -.-> lab-117690{{"`Java Heap Memory Error`"}} java/variables -.-> lab-117690{{"`Java Heap Memory Error`"}} java/while_loop -.-> lab-117690{{"`Java Heap Memory Error`"}} java/system_methods -.-> lab-117690{{"`Java Heap Memory Error`"}} end

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