Video in progress
After every redeploy Metaspace grows, and eventually we get OutOfMemoryError: Metaspace. How do you find the cause?
It's usually a classloader leak: someone (a ThreadLocal, a running thread, a JDBC driver registration, a static cache) holds a reference to the old application's ClassLoader, so all its classes can't be unloaded. In a heap dump you need to find the path from the old loader to a GC root.
📖 Answer
A class is unloaded only when the ClassLoader that loaded it, along with all its classes and objects, becomes unreachable. One strong reference, and thousands of the application's classes stay in Metaspace. Each redeploy adds another copy.
Where it shows up:
- redeploying a WAR to Tomcat/WildFly;
- plugin systems, scripting engines (Groovy), libraries that generate classes dynamically;
- Spring DevTools restart (in dev);
- code that creates a new proxy/class on every request (for example, a new
GroovyClassLoaderor a CGLIBEnhancerwith no cache on every call).
Diagnostics:
jcmd <pid> VM.classloader_statsorjcmd <pid> VM.metaspace: the number of loaders and how much each one occupies.-Xlog:class+unload: whether classes are being unloaded at all.- A heap dump after a redeploy, then Eclipse MAT: find the old application's loader in the list of
ClassLoaders (in Tomcat, aParallelWebappClassLoaderwithstarted=false), then "Path to GC Roots → exclude weak/soft references".
The usual culprits:
- ThreadLocal: a pool thread (the container's) holds the value, and the value is an application class;
- threads: a
TimerorExecutorServicethe application created and didn't shut down; the thread'scontextClassLoaderis the old loader; - a JDBC driver: registered in
DriverManagerand not deregistered; - static caches in the JDK/libraries:
ResourceBundle, bean introspection caches, logging frameworks; - a shutdown hook, a JMX MBean,
java.beans.PropertyEditorManager.
The fix: when the application stops (ServletContextListener.contextDestroyed, Spring @PreDestroy), shut down the executors, remove() the ThreadLocals, and deregister the driver. Tomcat's leak detector logs name many of these.
The most correct way: not redeploying into containers but immutable deploys (a new container/pod, and the old process dies completely), which removes this whole class of problems. Capping -XX:MaxMetaspaceSize also helps: the leak then shows up as a fast, clear error rather than "eating the whole server's memory".
Sign up to mark studied questions and save your progress.