java.lang.OutOfMemoryError: Java heap space
The JVM ran out of heap memory.
Why this happens
The JVM allocates a fixed maximum amount of heap memory at startup (default varies by platform). When your application tries to allocate an object and the garbage collector cannot free enough space, this error is thrown. It usually indicates either a memory leak or that your application genuinely needs more memory than allocated.
Fix 1: Increase heap size
java -Xmx2g -Xms512m MyApp
-Xmx2gβ max heap 2GB-Xms512mβ initial heap 512MB
Fix 2: Find memory leaks
Common causes:
- Collections that grow without bounds
- Static references holding large objects
- Unclosed resources (streams, connections)
// β Memory leak β list grows forever
static List<byte[]> cache = new ArrayList<>();
void process() {
cache.add(new byte[1024 * 1024]);
}
Fix 3: Use a profiler
# Generate heap dump on OOM
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp MyApp
Then analyze with VisualVM or Eclipse MAT.
Alternative solutions
Use weak references for caches so the GC can reclaim memory when needed:
Map<String, SoftReference<byte[]>> cache = new HashMap<>();
Stream large datasets instead of loading everything into memory β use BufferedReader, database cursors, or pagination.
Prevention
- Set
-Xmxexplicitly in production rather than relying on JVM defaults. - Monitor heap usage with JMX metrics and alert before OOM occurs.
Related: Java: NullPointerException fix Β· Kubernetes: OOMKilled fix