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.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.
test {
jvmArgs '-XX:MaxMetaspaceSize=512m'
forkEvery = 100 // recycle worker JVMs to reclaim Metaspace
}Cut distinct context configurations
- Reuse one Spring context across tests (avoid per-test
@DirtiesContext/unique config) so fewer classes load. - Limit dynamic proxy/mock generation in tight loops.
- Recycle worker JVMs (
forkEvery) so Metaspace is reclaimed periodically.
How to prevent it
- Share Spring test contexts, avoid needless
@DirtiesContext, capMaxMetaspaceSize, and recycle worker JVMs so class metadata cannot grow unbounded.