Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

After several hot redeploys of a web application in a shared Tomcat, the server fails with OutOfMemoryError: Metaspace. Tomcat logs warnings that the web application created a ThreadLocal and failed to remove it. Explain the leak.

Tomcat's worker threads belong to the server, not to the web application, so they survive a redeploy. Their ThreadLocalMaps still hold values whose classes were loaded by the old application's class loader, and since every object references its class and every class references its loader, those values keep the whole old loader, and every class it loaded, reachable. Each redeploy leaks one more class loader until metaspace is full. We fix it by removing ThreadLocals in finally blocks or at shutdown and by upgrading libraries that leak, and in production we prefer full restarts over hot redeploys.

Why this question is asked

Hot redeploy, replacing a WAR in a running Tomcat without restarting the JVM, looks like a time saver, and it is common in shared application servers. The class loader leak it causes is a classic, and the error appears days or redeploys after the real cause, which makes it confusing. Interviewers ask it because it tests our understanding of how classes are tied to class loaders and how a single stray reference can pin megabytes of metadata. In this answer, we will recap metaspace and the web application class loader, follow the reference chain that leaks it, read Tomcat's warning, and go through the fixes.

1A Quick Recap: Metaspace and the Web Application Class Loader

Metaspace is native memory outside the Java heap where the JVM keeps class metadata: the structure of each class, its methods, its bytecode and its constant pool. A class's metadata can only be freed when its class loader is garbage collected, and a class loader can only be collected when nothing references it, none of its classes and none of their instances.

Tomcat gives each web application its own class loader, the WebappClassLoader, which loads the classes from WEB-INF/classes and WEB-INF/lib. Server classes and the Tomcat thread pool are loaded by Tomcat's own loaders. On undeploy, Tomcat drops its references to the old WebappClassLoader and expects the garbage collector to free it, along with the 20,000 or so classes of a typical Spring application, which can be 100 to 200 MB of metaspace.

2Following the Reference Chain That Leaks the Loader

Tomcat's request threads are created by the server and reused across applications and redeploys. Suppose our application sets a ThreadLocal on those threads and never removes it. After the redeploy, the thread's ThreadLocalMap still has an entry whose value is an instance of one of our classes, say com.example.UserContext.

That instance refers to its class, UserContext. The class refers to its defining loader, the old WebappClassLoader. The loader refers to every class it ever loaded. So one small object on one server thread keeps the entire old application's classes in metaspace. The new deployment loads all those classes again with a new loader, metaspace grows by another 150 MB, and after enough redeploys the JVM throws OutOfMemoryError: Metaspace, or, if no MaxMetaspaceSize is set, the process keeps growing until the container is killed.

Step throughOne stale value pins the old application
  1. Tomcat worker threadcreated by the server, outlives every web application
  2. ThreadLocalMap entryvalue never removed by the old application
  3. UserContext instancean object of an old application class
  4. UserContext.classevery object refers to its class
  5. Old WebappClassLoaderevery class refers to its loader
  6. All classes of the old appabout 150 MB of metaspace that can never be freed

6 layers, from the top down. Step through them one at a time.

3Reading Tomcat's Warning

Tomcat checks for this on undeploy and logs a warning for each leftover ThreadLocal it finds on its threads. The message names the key and value types, which usually identifies the culprit directly.

Text
SEVERE [main] org.apache.catalina.loader.WebappClassLoaderBase.checkThreadLocalMapForLeaks
The web application [orders] created a ThreadLocal with key of type [java.lang.ThreadLocal]
(value [java.lang.ThreadLocal@1b2c3d4e]) and a value of type [com.example.UserContext]
(value [com.example.UserContext@5f6a7b8c]) but failed to remove it when the web application was stopped.
Threads are going to be renewed over time to try and avoid a probable memory leak.

Notice the last sentence. Tomcat's ThreadLocalLeakPreventionListener, enabled in the default server.xml, renews the worker threads of the stopped context's executor over time, so threads with stale ThreadLocals are eventually replaced and the old loader can be collected. That mitigates the leak but depends on configuration and timing, and it does not cover threads that other libraries start themselves, such as a scheduler or a connection pool's housekeeping thread, whose context class loader may point at the old application.

4Confirming It With a Heap Dump

To prove the diagnosis, we redeploy twice, then take a heap dump with jcmd <pid> GC.heap_dump. In Eclipse Memory Analyzer, a class histogram filtered on WebappClassLoader shows several instances instead of one; the old ones have their state set to stopped. Asking for the shortest path to GC roots from an old loader, excluding weak references, shows the chain we described: a thread, its threadLocals, an entry, a value of one of our classes. MAT's duplicate classes view also shows the same class names loaded once per leaked loader. On the metaspace side, jcmd <pid> VM.classloader_stats lists loaders with their class counts and sizes, so leaked loaders appear as repeated entries of the same type with thousands of classes each.

5Fixing the Leak and Avoiding It

In our own code, every ThreadLocal.set gets a matching remove in a finally block, usually in a filter around the request. ThreadLocals that are not tied to a request, such as caches, are cleared in a ServletContextListener's contextDestroyed method or a Spring @PreDestroy method when the application stops, and any threads or executors we started are shut down there too.

Java
@WebListener
public class CleanupListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent e) {
UserContextHolder.clear(); // our own static holders
reportExecutor.shutdownNow(); // threads we started
// Deregister JDBC drivers loaded by this application, another common leak
DriverManager.drivers()
.filter(d -> d.getClass().getClassLoader() == getClass().getClassLoader())
.forEach(d -> { try { DriverManager.deregisterDriver(d); } catch (SQLException ignored) { } });
}
}

Many leaks come from libraries rather than our code: older logging frameworks, JDBC drivers registered with DriverManager, XML and JSON libraries with internal ThreadLocal caches, and threads started by client libraries. The Tomcat warning names the classes, and upgrading or properly shutting down those libraries is often the fix.

The most reliable fix, though, is operational. In production we avoid hot redeploys and restart the JVM for every release, which is what container platforms do anyway: each version runs in a fresh process, so a leaked class loader cannot survive. Setting -XX:MaxMetaspaceSize to a sensible limit makes any remaining leak fail fast and visibly instead of slowly consuming the host's memory.

6Follow-up questions

Why is metaspace growing rather than the heap?

The leaked objects themselves are small, so the heap grows only a little. What is large is the class metadata of every class the old loader defined, and that lives in metaspace. Each leaked application copy adds its full set of classes there, which is why metaspace, not the heap, runs out first.

Does setting MaxMetaspaceSize cause the error?

It makes the error appear, but it does not cause the leak. By default metaspace is not capped, so without the limit the JVM keeps allocating native memory until the operating system or container limit kills the process. With a limit, we get a clear OutOfMemoryError: Metaspace and a chance to take diagnostics, which is better.

Are thread context class loaders part of this problem too?

Yes. Every thread has a context class loader, and threads that a web application starts, or that a library starts during a request, inherit the web application's loader as their context loader. If such a thread keeps running after undeploy, it pins the old loader even without any ThreadLocal. Shutting those threads down on stop is part of the fix.

7Conclusion

In this answer, we saw that metaspace holds class metadata that is freed only when a class loader becomes unreachable, and that each Tomcat web application has its own loader. A ThreadLocal value left on a server thread references an object, its class and the old loader, keeping every class of the old deployment alive, so each redeploy leaks another loader until metaspace fills. We read Tomcat's warning, confirmed the chain with a heap dump and class loader statistics, fixed it with finally blocks and shutdown cleanup and library upgrades, and preferred full restarts in production.

What to say in the interviewAbout 90 seconds aloud

Open with

The key is that Tomcat's worker threads belong to the server and survive a redeploy, while our classes belong to the web application's class loader. If our code, or a library, puts a value into a ThreadLocal on those threads and never removes it, the thread's ThreadLocalMap still holds an object of one of our classes after undeploy.

Then, if they want more

That object references its class, the class references the old WebappClassLoader, and the loader references every class it loaded, so the whole previous version of the application stays in metaspace. Each hot redeploy loads a fresh copy of every class with a new loader and leaks the old one, perhaps 150 megabytes each time, until we hit OutOfMemoryError: Metaspace.

Tomcat's warning tells us exactly this and names the key and value types. To confirm, I would take a heap dump after a couple of redeploys, find several WebappClassLoader instances, and look at the path to GC roots from an old one, which leads through a thread's threadLocals.

The fix is to remove every ThreadLocal in a finally block, clean up static holders, executors and JDBC drivers in contextDestroyed, and upgrade libraries the warnings point at. But in production I would avoid hot redeploys altogether and restart the JVM for each release, as container deployments do, and set MaxMetaspaceSize so any remaining leak fails fast.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "After several hot redeploys of a web application in a shared Tomcat, the server fails...": https://scrivio-interview-library.netlify.app/java/concurrency-problems/aee82c8c1e/