Skip to content
Latchkey

Gradle "OutOfMemoryError: Metaspace" in CI

Metaspace holds loaded class metadata, separate from the heap. A Gradle daemon that loads many plugins and build scripts (or one reused across builds) can exhaust Metaspace even when heap is fine.

What this error means

The build fails with "java.lang.OutOfMemoryError: Metaspace", often mid-configuration or during test class loading, not tied to a specific task output.

Gradle
> Task :app:test FAILED
java.lang.OutOfMemoryError: Metaspace
	at java.base/java.lang.ClassLoader.defineClass1(Native Method)
	at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:...)

Common causes

MaxMetaspaceSize is capped too low

A tight -XX:MaxMetaspaceSize in org.gradle.jvmargs fills up once many classes are loaded.

A long-lived daemon accumulates classes

A reused daemon keeps loading classes across builds without unloading, slowly filling Metaspace.

How to fix it

Raise MaxMetaspaceSize and use a fresh JVM

  1. Increase -XX:MaxMetaspaceSize in org.gradle.jvmargs.
  2. Run with --no-daemon so classes are not accumulated across builds.
  3. Give test forks their own Metaspace budget if they load many classes.
gradle.properties
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=1g
org.gradle.daemon=false

Set Metaspace for test forks

If tests exhaust Metaspace, raise it on the forked test JVM specifically.

build.gradle.kts
tasks.test {
    jvmArgs("-XX:MaxMetaspaceSize=512m")
}

How to prevent it

  • Set a generous -XX:MaxMetaspaceSize in org.gradle.jvmargs.
  • Use --no-daemon in CI so classes are not accumulated across builds.
  • Budget Metaspace for forked test JVMs separately.

Frequently asked questions

What causes ""OutOfMemoryError: Metaspace""?
A tight -XX:MaxMetaspaceSize in org.gradle.jvmargs fills up once many classes are loaded.
How do I fix "OutOfMemoryError: Metaspace"?
Raise MaxMetaspaceSize and use a fresh JVM

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card