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.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →