The java.lang.OutOfMemoryError: Java heap space error occurs when the Java Virtual Machine (JVM) does not have enough memory allocated to store objects and data in the heap.


Reasons for OutOfMemoryError: Java heap space:

1.    Large object or data size:

If your program is dealing with large amounts of data or objects, it can quickly consume the available heap space.

2.    Memory leaks:

If your program has memory leaks, it means that objects are not being properly garbage collected, leading to increased memory usage over time.

3.    Insufficient heap size:

If the heap size is not large enough to accommodate the memory requirements of your program, it can result in an OutOfMemoryError.

 

Solutions for OutOfMemoryError: Java heap space:

1.    Increase heap size:

You can allocate more memory to the JVM heap by setting the -Xmx flag. For example, java -Xmx2g MyClass sets the maximum heap size to 2 gigabytes.

2.    Optimize memory usage:

Review your code and identify areas where memory usage can be optimized. Close resources properly, use efficient data structures, and avoid unnecessary object creation.

3.    Stream and batch processing:

For large datasets, consider using stream processing or batch processing techniques to process data in smaller chunks instead of loading everything into memory at once.

4.    Analyze and fix memory leaks:

Use profilers and memory analysis tools to identify and fix memory leaks in your code. Ensure that objects are properly released and no unnecessary references are retained.

Example:

import java.util.ArrayList;

import java.util.List;

public class OutOfMemoryExample {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();      

        try {

            while (true) {

                String largeString = new String(new char[1000000]);

                list.add(largeString);

            }

        } catch (OutOfMemoryError e) {

            System.out.println("Out of memory error occurred.");

        }

    }

}


In the above example, a large number of String objects are created and added to the List. Eventually, the program will run out of heap space and throw an OutOfMemoryError. To resolve this issue, you can either increase the heap size using the -Xmx flag or optimize the code to reduce memory usage.

Reason: Large object or data size

Example:

import java.util.ArrayList;

import java.util.List;


public class LargeDataExample {

    public static void main(String[] args) {

        List<Integer> largeList = new ArrayList<>();

        for (int i = 0; i < Integer.MAX_VALUE; i++) {

            largeList.add(i);

        }

    }

}

Solution:

In STS, you can modify the heap size by adjusting the VM arguments in the Run Configuration.

ü  Right-click on your Java class file and select "Run As" > "Run Configurations...".

ü  Select your Java Application configuration.

ü  Go to the "Arguments" tab.

ü  In the "VM arguments" field, add -Xmx2g to set the maximum heap size to 2GB.

Click "Apply" and "Run" to execute the application with the increased heap size.

 

Reason: Memory leaks - Not releasing objects properly

Example:

import java.util.ArrayList;

import java.util.List;

 

public class MemoryLeakExample {

    private static List<Object> objectList = new ArrayList<>();

    public static void main(String[] args) {

        while (true) {

            Object object = new Object();

            objectList.add(object);

        }

    }

}

 

Solution:

ü  Use profilers and memory analysis tools available in STS to identify and fix memory leaks in your code.

ü  Ensure that objects are properly released when they are no longer needed.


Reason: Insufficient heap size

Example:

import java.util.ArrayList;

import java.util.List;

public class InsufficientHeapSizeExample {

    public static void main(String[] args) {

        List<String> stringList = new ArrayList<>();

        while (true) {

            String largeString = "This is a large string that consumes a lot of memory";

            stringList.add(largeString);

        }

    }

}


Remember to carefully analyze your specific application and determine the best approach to address the OutOfMemoryError based on the underlying cause. Based on above solution you can easily sove java errors.