java.lang.OutOfMemoryError: Java heap space
The JVM ran out of heap memory.
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.