OutOfMemoryError ☕ Java

java.lang.OutOfMemoryError: Java heap space

The JVM ran out of heap memory and garbage collection couldn’t free enough.

Seen on: Java Android

Meaning

Either the heap (-Xmx) is too small for the workload, or the application leaks memory (objects stay referenced). Variants: “GC overhead limit exceeded”, “Metaspace”, “unable to create native thread”.

Common causes

  • Heap too small for the workload
  • Memory leak (static collections, caches without eviction, listeners)
  • Loading huge files/result sets into memory
  • Container memory limit lower than JVM assumes

⚡ Quick fix

  1. Increase heap: -Xmx2g (or -XX:MaxRAMPercentage=75 in containers)
  2. Capture a heap dump: -XX:+HeapDumpOnOutOfMemoryError and analyze with Eclipse MAT
  3. Stream large data instead of loading it

Detailed fix by platform

Java

  1. In Docker/Kubernetes use -XX:MaxRAMPercentage so the heap respects the container limit.

Android

  1. Gradle builds: set org.gradle.jvmargs=-Xmx4g in gradle.properties.

How to diagnose

  1. Variant — Heap, Metaspace, GC overhead or native threads?
  2. Trend — Does memory grow steadily (leak) or spike (load)?
  3. Heap dump — Which objects dominate?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.