BackendBench
Coffee

Home โ€บ Java exceptions โ€บ OutOfMemoryError

Error ยท java.lang

OutOfMemoryError: causes and fixes

The JVM could not allocate memory: heap space, metaspace, direct buffers, native threads or GC overhead.

What it looks like

java.lang.OutOfMemoryError: Java heap space

Extends VirtualMachineError in java.lang.

What it means

The text after the colon tells you which area ran out. Java heap space means live objects fill the heap. GC overhead limit exceeded means the collector is spending almost all its time and reclaiming almost nothing. Metaspace means too many classes were loaded. Unable to create native thread means the OS refused another thread. Direct buffer memory means off-heap buffers filled their limit. Each has a different fix, so read the message before changing flags.

Common causes

How to fix it

  1. Take a heap dump on failure (-XX:+HeapDumpOnOutOfMemoryError) and open it in Eclipse MAT or VisualVM to see what holds the memory.
  2. Stream or page large data instead of loading it all; bound caches with a maximum size and expiry.
  3. Size the heap against the container limit; see the JVM memory calculator.
  4. Add -XX:+ExitOnOutOfMemoryError so an orchestrator restarts the process instead of leaving it half dead.

Broken and fixed

fails
List<Row> all = repo.findAll(); // millions of rows in one list
works
try (Stream<Row> rows = repo.streamAll()) {
    rows.forEach(this::process);
}

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

In Kubernetes a pod killed with exit code 137 is not an OutOfMemoryError: the container limit was exceeded by heap plus non-heap memory and the kernel killed the process. Check both.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is OutOfMemoryError a checked or unchecked exception?

OutOfMemoryError is an Error (it extends VirtualMachineError). Errors signal serious problems in the JVM or environment; applications normally should not catch them, and ordinary catch (Exception e) blocks will not.

Which package is OutOfMemoryError in?

It lives in java.lang, so the import is import java.lang.OutOfMemoryError; (java.lang needs no import).

What is the first thing to check when I see OutOfMemoryError?

Read the message and the first stack trace line in your own code. The usual causes are: A memory leak: a static map or cache that only grows, listeners never removed, ThreadLocals in thread pools; and Loading too much at once: a query without paging, reading a whole large file or response into memory.

Related exceptions

More tools you might need