Skip to content
Latchkey

Maven "OutOfMemoryError: Metaspace" During Build - Fix MAVEN_OPTS

The Maven JVM ran out of Metaspace, the area that holds loaded class metadata. Heavy plugin sets, annotation processors, and large multi-module reactors load many classes and can exceed the Metaspace ceiling.

What this error means

The build fails with java.lang.OutOfMemoryError: Metaspace, often mid-reactor on a large multi-module project or while a code-generation plugin loads many classes. Heap may be plentiful; Metaspace is what is exhausted.

mvn output
[ERROR] Java heap dumped
java.lang.OutOfMemoryError: Metaspace
  at java.base/java.lang.ClassLoader.defineClass1(Native Method)
[INFO] BUILD FAILURE

Common causes

Metaspace ceiling too low for the class load

A capped -XX:MaxMetaspaceSize (or a small default in a constrained container) is exhausted by the volume of classes loaded across many plugins and modules.

Class-heavy plugins and processors

Annotation processors, bytecode tools, and large frameworks load thousands of classes. In a single long-lived Maven JVM, that metadata accumulates.

How to fix it

Raise Metaspace via MAVEN_OPTS

Give the Maven JVM more Metaspace (and a heap dump on OOM for diagnosis).

Terminal
export MAVEN_OPTS="-Xmx2g -XX:MaxMetaspaceSize=1g -XX:+HeapDumpOnOutOfMemoryError"
mvn -B clean verify

Fork heavy work into separate JVMs

Run tests in a forked VM with its own bounded memory so the main Maven JVM is not the one accumulating class metadata.

pom.xml (surefire)
<configuration>
  <forkCount>1</forkCount>
  <reuseForks>false</reuseForks>
  <argLine>-XX:MaxMetaspaceSize=512m</argLine>
</configuration>

How to prevent it

  • Set -XX:MaxMetaspaceSize in MAVEN_OPTS relative to the runner, fork test JVMs with bounded memory, and use a larger runner for class-heavy reactors.

Frequently asked questions

What causes "Maven "OutOfMemoryError: Metaspace""?
A capped -XX:MaxMetaspaceSize (or a small default in a constrained container) is exhausted by the volume of classes loaded across many plugins and modules.
How do I fix Maven "OutOfMemoryError: Metaspace"?
Give the Maven JVM more Metaspace (and a heap dump on OOM for diagnosis).
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