OutOfMemoryError: Java Heap Space

java.lang.OutOfMemoryError: Java heap space

Quick Answer

The JVM has run out of heap memory. You are either allocating too many objects, have a memory leak, or need to increase the heap size.

Why This Happens

The JVM allocates objects on the heap. When the garbage collector cannot free enough memory to satisfy a new allocation, this error is thrown. Common causes include loading large datasets into memory, memory leaks from unclosed resources, or growing collections without bounds.

The Problem

List<byte[]> list = new ArrayList<>();
while (true) {
    list.add(new byte[1_000_000]); // Unbounded allocation
}

The Fix

// Process data in chunks instead of loading everything
try (BufferedReader reader = new BufferedReader(new FileReader("large.txt"))) {
    String line;
    while ((line = reader.readLine()) != null) {
        processLine(line); // Process one line at a time
    }
}

Step-by-Step Fix

  1. 1

    Identify the allocation source

    Use a heap dump (jmap -dump) or profiler to find which objects consume the most memory.

  2. 2

    Check for memory leaks

    Look for collections that grow without bound, unclosed streams, or static fields holding large objects.

  3. 3

    Fix the leak or increase heap

    Fix memory leaks by closing resources, limiting collection sizes, or processing data in streams. As a temporary fix, increase heap with -Xmx.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free