← Back to Error Lab

java.lang.OutOfMemoryError: Java heap space

Published 2026-04-10

Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.

Root Cause

This fatal error means the Java Virtual Machine (JVM) has exhausted the memory allocated for the heap, which is where objects are stored. The garbage collector (GC) is unable to free enough memory to accommodate new object creation. This can happen for two main reasons. The benign reason is that the application simply requires more memory than the default allocation to process large datasets (e.g., loading a massive CSV file into memory all at once). The malicious reason is a memory leak: the application is holding onto references to objects that are no longer needed (e.g., adding objects to a static List and never clearing it), preventing the GC from reclaiming them. Over time, these 'zombie' objects fill the heap until the application crashes.

Fix / Solution

If it's a legitimate need for more memory, increase the JVM heap size using the `-Xmx` flag (e.g., `-Xmx4g` for 4GB). If you suspect a memory leak, generate a heap dump (`-XX:+HeapDumpOnOutOfMemoryError`) and analyze it using tools like Eclipse MAT or VisualVM to identify which objects are consuming the memory and what is holding references to them. Optimize code to process data in streams rather than loading everything into memory.

Code Snippet

// ❌ Broken (Loads entire file into memory at once)
List<String> allLines = Files.readAllLines(Paths.get("huge-file.txt"));
for (String line : allLines) {
    process(line);
}

// ✅ Fixed (Processes file line by line using streams)
try (Stream<String> lines = Files.lines(Paths.get("huge-file.txt"))) {
    lines.forEach(line -> process(line));
}

// JVM Argument to increase max heap size to 2 Gigabytes
// java -Xmx2g -jar myapp.jar