Video in progress

Strong Middle ⚙️ JVM and memory

After you redeploy on an application server, why does the old ClassLoader not get collected, and how do you find it in a heap dump?

It is enough for one class or object of the old ClassLoader to be held by something, and all the classes it loaded stay in metaspace. The usual culprits: an uncleaned ThreadLocal, a thread that wasn't stopped, a JDBC driver registration, a static cache in a shared loader.

📖 Answer

A class keeps a reference to the loader that loaded it, and the loader keeps all its loaded classes. So one "escaped" object holds thousands of classes of the whole webapp. With every redeploy metaspace grows by another few hundred MB, and after a few deploys you get OutOfMemoryError: Metaspace.

Typical causes:

  • a thread or ScheduledExecutorService started inside the webapp but not stopped in contextDestroyed;
  • ThreadLocal values left on Tomcat threads;
  • a JDBC driver registered in DriverManager (which lives in the shared loader);
  • a webapp object added to a static cache or listener list in a shared library.

Searching in the heap dump (MAT):

  1. In the histogram I filter for org.apache.catalina.loader.ParallelWebappClassLoader. If there are two or more instances for one webapp, the older one has leaked.
  2. On the old one (in Tomcat you tell it apart by started=false or a state field), run Path to GC Roots, exclude weak/soft.
  3. The path is often like this: Thread "pool-3-thread-1" → threadLocals → ... → MyClass → loader.

Tomcat itself helps too: on undeploy it writes warnings to the log like "appears to have started a thread named ... but has failed to stop it". The Manager application also has a "Find leaks" button.

With a Spring Boot fat jar, every deploy is a new process, so this problem almost disappears. But it still shows up in plugin systems and script engines.