0
0
JavaDebug / FixBeginner · 4 min read

How to Fix OutOfMemoryError in Java: Simple Solutions

An OutOfMemoryError in Java happens when your program uses more memory than the JVM allows. To fix it, you can increase the heap size with JVM options like -Xmx or optimize your code to use less memory by fixing leaks or reducing large object creation.
🔍

Why This Happens

An OutOfMemoryError occurs when the Java Virtual Machine (JVM) runs out of memory to allocate new objects. This usually happens if your program creates too many objects without releasing them, or if the heap size is too small for the workload.

java
import java.util.ArrayList;

public class MemoryLeakExample {
    public static void main(String[] args) {
        ArrayList<int[]> list = new ArrayList<>();
        while (true) {
            // Keep adding large arrays to the list without removing them
            list.add(new int[1_000_000]);
        }
    }
}
Output
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
🔧

The Fix

To fix this error, you can increase the JVM heap size using the -Xmx option to allow more memory. Also, fix your code to avoid holding onto large objects unnecessarily. For example, stop adding objects endlessly or clear collections when done.

java
import java.util.ArrayList;

public class FixedMemoryUsage {
    public static void main(String[] args) throws InterruptedException {
        ArrayList<int[]> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new int[1_000_000]);
            Thread.sleep(100); // simulate work
        }
        list.clear(); // free memory
        System.out.println("Memory used safely and cleared.");
    }
}
Output
Memory used safely and cleared.
🛡️

Prevention

To avoid OutOfMemoryError in the future, follow these tips:

  • Set appropriate heap size with JVM options like -Xms and -Xmx.
  • Use profiling tools to find memory leaks.
  • Release references to unused objects so garbage collection can free memory.
  • Avoid creating large objects in loops without clearing.
  • Use efficient data structures and algorithms to reduce memory use.
⚠️

Related Errors

Other memory-related errors include:

  • StackOverflowError: Happens when the call stack is too deep, often due to infinite recursion.
  • GC Overhead Limit Exceeded: JVM spends too much time garbage collecting with little memory freed.

Fixes involve optimizing recursion, increasing stack size, or tuning garbage collection.

Key Takeaways

Increase JVM heap size with -Xmx to allow more memory if needed.
Fix code to avoid holding references to large objects unnecessarily.
Use profiling tools to detect and fix memory leaks early.
Clear or reuse collections to prevent unbounded memory growth.
Understand related errors like StackOverflowError for better debugging.