Skip to content
  1. LuzineDebug
  2. Java, Kotlin & .NET
  3. Exception in thread "main" java.lang.OutOfMemory…
Java, Kotlin & .NET Advanced ≈ 30 min to fix

Fix "java.lang.OutOfMemoryError: Java heap space" (and GC overhead limit exceeded)

Error message
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
  • java.lang.OutOfMemoryError: GC overhead limit exceeded
  • Execution failed for task ':app:mergeDexDebug'. > java.lang.OutOfMemoryError: Java heap space
  • java.lang.OutOfMemoryError: Metaspace
  • Exception in thread "http-nio-8080-exec-3" java.lang.OutOfMemoryError: Java heap space
  • Expiring Daemon because JVM heap space is exhausted
In short

The JVM has no room left in its heap to create an object. If the need is legitimate, raise the maximum size with -Xmx (or org.gradle.jvmargs for a Gradle build); if memory keeps climbing and never drops, it is a leak: take a heap dump with -XX:+HeapDumpOnOutOfMemoryError and analyse it.

Be the first to confirm this fix

What this error means

Java objects live in the heap, whose maximum size is fixed when the JVM starts: by default a quarter of the available RAM, or the value of -Xmx. The garbage collector (GC) frees objects that are no longer referenced. When an allocation fails even after a full GC, the JVM throws OutOfMemoryError: Java heap space. This happens when the data really exceeds the heap (large file, huge query) or when objects stay referenced for no reason (a leak). The GC overhead limit exceeded variant means the JVM spends more than 98% of its time in GC to recover less than 2% of the heap: the symptom is the same.

Common causes

  1. Heap too small for the load: low -Xmx, container with little memory, or a Gradle / Android build with the default org.gradle.jvmargs.
  2. Loading everything into memory: Files.readAllBytes on a big file, findAll() on a table with millions of rows, a huge HTTP or JSON response read in one go.
  3. Memory leak: a static collection or unbounded cache that grows on every request, listeners never removed, ThreadLocal values not cleaned up in a thread pool.
  4. Loop that creates objects endlessly: recursion over cyclic data, string concatenation or a list filled by mistake in an infinite loop.

Step-by-step fix

  1. Identify which JVM runs out of memory

    Your application, the Gradle daemon, the Kotlin daemon, Maven or the tests? The thread name and the task in the log tell you. Then check the current heap size.

    bash
    jcmd                       # list running JVMs and their PIDs
    jcmd 12345 GC.heap_info    # current heap usage
    jstat -gcutil 12345 1000   # GC activity every second
    java -XX:+PrintFlagsFinal -version | grep MaxHeapSize
  2. Raise the application heap

    If the memory need is legitimate, give it more heap. In a container, prefer MaxRAMPercentage, which follows the container memory limit, over a fixed -Xmx. JAVA_TOOL_OPTIONS applies to any JVM launched.

    bash
    java -Xms512m -Xmx2g -jar app.jar
    # in a container
    java -XX:MaxRAMPercentage=75.0 -jar app.jar
    # any JVM (tests, tools)
    export JAVA_TOOL_OPTIONS="-Xmx2g"
  3. Raise the Gradle / Android build memory

    For an error during mergeDexDebug, compileKotlin or a Gradle build, set the daemon memory in gradle.properties at the project root, then restart the daemons with ./gradlew --stop. For Maven, use MAVEN_OPTS="-Xmx2g".

    ini
    # gradle.properties
    org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g -Dfile.encoding=UTF-8
    kotlin.daemon.jvmargs=-Xmx2g
  4. Capture a heap dump

    If the problem comes back despite more memory, it is probably a leak. Have the JVM write a dump automatically when the error happens, or take one by hand on a JVM that keeps growing. The .hprof file contains in-memory data: treat it as sensitive.

    bash
    java -Xmx2g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/dumps -jar app.jar
    # manual dump of a running JVM
    jcmd 12345 GC.heap_dump /tmp/dumps/heap.hprof
  5. Analyse the dump

    Open the .hprof file in Eclipse Memory Analyzer (MAT), VisualVM or the IntelliJ IDEA profiler. MAT’s "Leak Suspects" report and the "Dominator Tree" view show which objects retain the most memory and the reference chain that keeps them alive.

  6. Fix the code

    Process data as a stream instead of loading everything, paginate queries and bound caches. Once the cause is fixed, memory should level off under load.

    java
    // stream a large file line by line
    try (Stream<String> lines = Files.lines(path)) {
        lines.forEach(this::process);
    }
    
    // paginate instead of findAll()
    Page<Order> page = orderRepository.findAll(PageRequest.of(0, 500));
    
    // bounded cache (Caffeine) instead of a static HashMap
    Cache<String, User> cache = Caffeine.newBuilder().maximumSize(10_000).build();

Did this fix work for you?

Confirm it in one click: it will rise for the next developers stuck on the same error.

Keep it from coming back

  • Enable -XX:+HeapDumpOnOutOfMemoryError in production so you always have a dump to analyse after an incident.
  • Monitor the heap and GC (Micrometer, Prometheus, JDK Flight Recorder): memory rising like a staircase without dropping signals a leak well before the crash.
  • Run load tests with realistic data volumes before going to production.

Frequently asked questions

Should I disable GC overhead limit exceeded with -XX:-UseGCOverheadLimit?

No: the option only delays the error, the JVM stays stuck in GC and then throws Java heap space. Raise the heap or fix the leak.

What value should I use for -Xmx?

Enough for the real measured peak, with a margin, and always below the RAM or the container limit: the JVM also uses off-heap memory (threads, metaspace, buffers). In a container, 70 to 80% through MaxRAMPercentage is a common starting point.

What is the difference between Java heap space and Metaspace?

Java heap space is about your objects. Metaspace is about class definitions: it fills up when too many classes are loaded (hot redeploys, proxy generation). Raise -XX:MaxMetaspaceSize or look for the classloader leak.

Useful tools for this error

More Java, Kotlin & .NET errors

All Java, Kotlin & .NET errors →