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.
> 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
- Increase
-XX:MaxMetaspaceSizeinorg.gradle.jvmargs. - Run with
--no-daemonso classes are not accumulated across builds. - Give test forks their own Metaspace budget if they load many classes.
org.gradle.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=1g
org.gradle.daemon=falseSet Metaspace for test forks
If tests exhaust Metaspace, raise it on the forked test JVM specifically.
tasks.test {
jvmArgs("-XX:MaxMetaspaceSize=512m")
}How to prevent it
- Set a generous
-XX:MaxMetaspaceSizeinorg.gradle.jvmargs. - Use
--no-daemonin CI so classes are not accumulated across builds. - Budget Metaspace for forked test JVMs separately.