Mr.AndroidShin / Dev Tools

Debugging log · Gradle

Gradle "Out of memory" / "JVM heap space is exhausted"

One of my larger projects started failing builds intermittently — fine one run, dead the next with a heap error, then a slow "expiring daemon" message. Intermittent memory failures are the worst kind because they feel random, but the cause is boringly consistent: the Gradle daemon's JVM simply doesn't have enough heap for what the build is asking of it.

The short version: the Gradle daemon runs in a JVM with a fixed maximum heap. A big project (lots of modules, R8, annotation processing) can exceed it. Give the daemon more heap via org.gradle.jvmargs in gradle.properties — but size it sensibly, don't just set it to your whole machine's RAM.

The error

Expiring Daemon because JVM heap space is exhausted

FAILURE: Build failed with an exception.
> java.lang.OutOfMemoryError: Java heap space
  (or: GC overhead limit exceeded)

You may see any of three faces of the same problem: Java heap space, GC overhead limit exceeded, or the daemon "expiring" and restarting. All three mean the same thing — the JVM ran out of usable heap.

The main fix — raise the daemon heap

In gradle.properties (project root, or the global one in your Gradle user home), set the max heap:

# gradle.properties
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g \
  -Dfile.encoding=UTF-8

-Xmx4g caps the heap at 4 GB. If 4 GB isn't enough for a very large project, 6 GB is a reasonable next step. Restart the daemon after changing this (./gradlew --stop) so the new setting takes effect — editing the file without stopping the old daemon is a common reason "nothing changed".

Don't over-allocate

It's tempting to set -Xmx to almost all your RAM, but that backfires. The daemon isn't the only thing running — the OS, Android Studio, the Kotlin daemon, and emulators all need memory too. Over-allocate and you push the whole machine into swapping, which makes builds slower and can cause new, stranger failures. A good rule of thumb is to leave several gigabytes for everything else; on a 16 GB machine, 4–6 GB for Gradle is usually the sweet spot.

Metaspace, not heap

If the error specifically says OutOfMemoryError: Metaspace, that's a different pool — class metadata, not objects. Raise -XX:MaxMetaspaceSize instead of (or alongside) -Xmx. Heavy annotation processing and lots of generated classes are the usual cause.

Reduce the pressure, not just the ceiling

More heap treats the symptom. A few settings reduce how much memory a build needs in the first place:

If builds fail only on CI but pass locally, the CI runner almost certainly has less RAM than your laptop. Set a CI-appropriate -Xmx for that environment rather than assuming your local value fits — a value that's comfortable on 32 GB can OOM on a 7 GB runner.

Heap sizes above are starting points — tune to your project size and the RAM actually available on the machine.