What it means
You see java.lang.OutOfMemoryError: Metaspace when the JVM cannot allocate more space for class metadata. Metaspace lives in native memory, outside the heap, so raising -Xmx does not help. For the other kinds of OOM read Fix OutOfMemoryError.
By default Metaspace has no upper limit, so it grows until the operating system refuses more memory. On a small VPS the result is often not this error at all but the Linux OOM killer (see here). Setting a limit makes the problem show up early and with a clear message.
1. Measure it
PID=$(pgrep -f catalina | head -1) # or your app
sudo -u tomcat jcmd $PID VM.metaspace | head -30
sudo -u tomcat jstat -gc $PID 5000 5 # MC = metaspace capacity, MU = used (KB)
A normal framework application uses 100 to 300 MB. Spring Boot with many starters, Hibernate and Jackson is on the upper side. Check the number after the application has run for a while. If MU keeps growing without stopping, you have a leak.
2. Set a limit
-XX:MaxMetaspaceSize=256m
Pick a number about 30 to 50 percent above what you measured. Where to put it: Tomcat memory settings or the ExecStart line of your Spring Boot service.
3. Redeploys are the usual leak
Every redeploy of a WAR on a running Tomcat creates a new classloader. If anything from the old version stays referenced (a thread, a JDBC driver registered in the system classloader, a static cache), the old classes are never freed. After a few redeploys metaspace is full. The fix is operational:
- Restart Tomcat after a deployment instead of hot redeploying. A restart takes seconds and resets everything.
- Put the JDBC driver in your application (WEB-INF/lib), not in Tomcat's
libfolder, or deregister it on shutdown. - Stop threads and executors your code started when the application stops.
- Look at the Tomcat log for the messages "The web application [x] appears to have started a thread named [y] but has failed to stop it" and "created a ThreadLocal ... but failed to remove it". These tell you exactly which library leaks.
4. Other causes
- Code generation at runtime. Libraries that create classes on the fly (some scripting, proxy and reflection libraries) can load thousands of classes if used wrongly, for example a new proxy for every request.
- Too many applications in one JVM. Each adds its own classes. Count them when you size the server.
5. Find what is loaded
sudo -u tomcat jcmd $PID VM.classloader_stats | sort -k2 -n -r | head
sudo -u tomcat jcmd $PID GC.class_histogram | head -30
A very large number of classloaders (hundreds of web application loaders for one application) confirms the redeploy leak. To go deeper take a heap dump and look at the classloader tree in a tool such as Eclipse MAT.
Questions about fix metaspace outofmemoryerror
Should I leave MaxMetaspaceSize unset?
On a dedicated large server it is fine. On a small VPS set it. A limit gives a clear error early instead of an unexplained kill by the operating system.
Last updated October 29, 2026.