Skip to content
Latchkey

Kotlin daemon "OutOfMemoryError: Metaspace" in CI

Metaspace holds class metadata, separate from the Java heap. A large Kotlin build (many modules, kapt/ksp generating classes) can exhaust the default Metaspace on the compile daemon, producing OutOfMemoryError: Metaspace even when heap is fine.

What this error means

The Kotlin compile daemon or Gradle daemon fails with "java.lang.OutOfMemoryError: Metaspace" and the compile task aborts, sometimes taking the daemon down with it.

Kotlin
> Task :app:compileKotlin FAILED
java.lang.OutOfMemoryError: Metaspace
    at java.base/java.lang.ClassLoader.defineClass1(Native Method)

Common causes

Default Metaspace too small for the build

A multi-module Kotlin build loads many classes; the daemon default Metaspace cap is exceeded, especially with annotation processors generating extra classes.

Metaspace accumulates across a long-lived daemon

A reused daemon that compiled many builds retains class metadata until Metaspace is full.

How to fix it

Raise MaxMetaspaceSize for daemon and Gradle

Set a larger Metaspace cap in gradle.properties for both the Gradle and Kotlin daemons.

gradle.properties
# gradle.properties
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1536m
kotlin.daemon.jvmargs=-Xmx2g -XX:MaxMetaspaceSize=1g

Restart daemons on OOM

  1. Stop lingering daemons so Metaspace resets.
  2. Re-run the build with the raised Metaspace cap.
  3. On self-hosted runners, avoid indefinitely reusing one daemon.
Terminal
./gradlew --stop
./gradlew build

How to prevent it

  • Set an explicit MaxMetaspaceSize sized for your module count.
  • Restart the Gradle/Kotlin daemons periodically on long-lived runners.
  • Reduce kapt usage (prefer ksp) to cut generated-class churn.

Frequently asked questions

What causes ""OutOfMemoryError: Metaspace" (Kotlin daemon)"?
A multi-module Kotlin build loads many classes; the daemon default Metaspace cap is exceeded, especially with annotation processors generating extra classes.
How do I fix "OutOfMemoryError: Metaspace" (Kotlin daemon)?
Set a larger Metaspace cap in gradle.properties for both the Gradle and Kotlin daemons.

Related guides

References

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