Skip to content
Latchkey

Java "OutOfMemoryError: Metaspace" in Tests in CI - Fix Class Metadata OOM

Metaspace holds class metadata, off-heap. A Metaspace OOM in tests usually comes from loading enormous numbers of classes - many Spring contexts, dynamic proxies, mocks, or reloaded classloaders - that exceed MaxMetaspaceSize or available native memory, sometimes due to a classloader leak.

What this error means

A test run fails with java.lang.OutOfMemoryError: Metaspace, often after many test classes, repeated Spring context loads, or heavy proxy/mock generation. Heap may be fine; Metaspace is the limit hit.

java
java.lang.OutOfMemoryError: Metaspace
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at org.springframework.cglib.core.ReflectUtils.defineClass(...)

Common causes

Too many classes/contexts loaded

Each distinct Spring test context, proxy, or mock loads classes into Metaspace. Many of them in one JVM exhaust it.

Classloader leak

Contexts/classloaders not released keep their classes pinned in Metaspace, so it grows without bound across the suite.

How to fix it

Raise MaxMetaspaceSize and reduce context churn

Give Metaspace more room and reuse the test context where possible.

build.gradle
test {
  jvmArgs '-XX:MaxMetaspaceSize=512m'
  forkEvery = 100   // recycle worker JVMs to reclaim Metaspace
}

Cut distinct context configurations

  1. Reuse one Spring context across tests (avoid per-test @DirtiesContext/unique config) so fewer classes load.
  2. Limit dynamic proxy/mock generation in tight loops.
  3. Recycle worker JVMs (forkEvery) so Metaspace is reclaimed periodically.

How to prevent it

  • Share Spring test contexts, avoid needless @DirtiesContext, cap MaxMetaspaceSize, and recycle worker JVMs so class metadata cannot grow unbounded.

Frequently asked questions

What causes ""OutOfMemoryError: Metaspace""?
Each distinct Spring test context, proxy, or mock loads classes into Metaspace. Many of them in one JVM exhaust it.
How do I fix "OutOfMemoryError: Metaspace"?
Give Metaspace more room and reuse the test context where possible.
Can Latchkey fix this automatically?
Yes. Latchkey runs your GitHub Actions on managed runners that detect this failure, apply the fix, and retry the job automatically - self-healing is on by default.

Related guides

References

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