OutOfMemoryError in Java — What It Means and How to Fix It

What Java's OutOfMemoryError means and how to fix it.

Published November 2, 2026

OutOfMemoryError means the JVM cannot allocate more memory, usually because the heap is full of objects still in use (a leak) or the heap is too small.

What it means and why it happens

Typical causes: unbounded caches or lists, loading huge files, memory leaks via static references or listeners, or too small -Xmx.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
java.lang.OutOfMemoryError: Java heap space

Practical examples

Code that triggers it

List<byte[]> list = new ArrayList<>();
while (true) list.add(new byte[1_000_000]);

The fix

// bound the cache and stream data
Map<String, Data> cache = new LinkedHashMap<>(100, 0.75f, true) {
    protected boolean removeEldestEntry(Map.Entry e) { return size() > 1000; }
};

Diagnose

java -Xmx512m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/app.hprof -jar app.jar
# analyse with Eclipse MAT or VisualVM

Common mistakes

  • Only raising -Xmx.
  • Static collections that grow forever.
  • Not taking a heap dump.

Key takeaways

  • OutOfMemoryError: OutOfMemoryError means the JVM cannot allocate more memory, usually because the heap is full of objects still in use (a leak) or the heap is too small.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Heap space vs Metaspace?

Heap holds objects; Metaspace holds class metadata and has its own OutOfMemoryError.

How do I find which line caused OutOfMemoryError?

The error message and stack trace show the file and line; start there and work backwards.

More Java articles