OutOfMemoryError
JavaFATALCriticalRuntime

JVM heap space exhausted

Quick Answer

Increase heap with -Xmx, identify leaks with a profiler, or process large data as a stream instead of loading it all into memory.

What this means

Thrown when the JVM cannot allocate an object because the garbage collector cannot free enough heap memory.

Why it happens
  1. 1Memory leak — objects retained in static collections indefinitely
  2. 2Loading entire large file into a byte array

Fix

Increase heap and enable GC logging

Increase heap and enable GC logging
java -Xmx4g -Xlog:gc* -jar app.jar

Why this works

GC logs reveal whether heap fills gradually (leak) or spikes suddenly (large allocation).

Code examples
Common leak: unbounded static mapjava
static Map<String, byte[]> cache = new HashMap<>();
// Items never evicted — heap fills up over time
Fix: bounded LinkedHashMapjava
Map<String, byte[]> cache = new LinkedHashMap<>(1000, 0.75f, true) {
    protected boolean removeEldestEntry(Map.Entry e) {
        return size() > 1000;
    }
};
Stream large filesjava
try (Stream<String> lines = Files.lines(path)) {
    lines.forEach(this::processLine); // O(1) memory
}
Sources
Official documentation ↗

Java SE Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Java errors