Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Deployment and Contexts

Class Loading in Tomcat

Understand Tomcat's class loader hierarchy: bootstrap, system, common and webapp loaders, why web apps load their own classes first, where to place JARs, and how class loader leaks happen.

"It works on my machine" in the Tomcat world often means a class-loading problem: two copies of the same library, a JAR in the wrong folder, or a ClassCastException between two classes with the same name. Tomcat uses its own class loader hierarchy so that web applications are isolated from each other and from the server, and understanding it turns many mysterious errors into one-minute fixes.

This lesson explains the hierarchy, the unusual delegation order used for web apps, where each kind of JAR should go and what a class loader leak is. A runnable simulation of the delegation rules finishes the lesson.

The hierarchy

flowchart TD
    B["Bootstrap<br/>JDK classes (java.*)"] --> S["System loader<br/>bootstrap.jar, tomcat-juli.jar"]
    S --> C["Common loader<br/>CATALINA_HOME/lib and CATALINA_BASE/lib"]
    C --> W1["Webapp loader: /shop<br/>WEB-INF/classes, WEB-INF/lib"]
    C --> W2["Webapp loader: /blog<br/>WEB-INF/classes, WEB-INF/lib"]

Each web application has its own loader. The common loader is shared by Tomcat and all apps.

In Tomcat 6 and later the old separate "server" and "shared" loaders are merged into common, unless you configure server.loader or shared.loader in conf/catalina.properties (empty by default). So in practice you have four levels:

  1. Bootstrap (JVM): java.*, javax.* from the platform modules.
  2. System: the class path of the launcher, bin/bootstrap.jar, bin/tomcat-juli.jar and CLASSPATH.
  3. Common: everything in lib. Visible to Tomcat's internals and all web apps.
  4. Webapp: WEB-INF/classes first, then every JAR in WEB-INF/lib. Visible to that application only.

Where to put a JAR

WEB-INF/lib Default: private to one app
CATALINA_BASE/lib Shared by all apps and Tomcat
JDBC driver for a pool lib, when Tomcat creates the pool

When in doubt, put it in the WAR.

1 / 2

The twist: web apps load their own classes first

Normal Java class loaders ask their parent first ("parent-first" delegation) and only load a class themselves if the parent does not have it. Tomcat's webapp class loader reverses this for most classes (the Servlet specification recommends it): it looks in its own WEB-INF/classes and WEB-INF/lib before asking the common loader. The exceptions:

  • Classes of the JRE (java.*, and the platform's javax.* packages) always come from the parent, so you cannot replace java.lang.String.
  • The Servlet, JSP, EL and WebSocket API packages (jakarta.servlet.* and friends) come from Tomcat even if you bundled a copy, because the container and your app must agree on those types. (Bundling them is still a bug: Tomcat can log a warning or reject the deployment.)

You can switch to parent-first for one context with <Loader delegate="true"/>, which is rarely needed.

The benefit is real isolation: /shop can use Hibernate 5 while /blog uses Hibernate 6 even though both sit in the same JVM.

Typical class-loading errors

Symptom Likely cause
ClassNotFoundException for your own class The class is not in WEB-INF/classes or a WEB-INF/lib JAR, or the JAR was filtered by the JAR scanner.
NoClassDefFoundError The class existed at compile time, but a dependency is missing at run time, or its static initializer failed earlier.
ClassCastException: X cannot be cast to X The same class was loaded by two loaders: for example a library in both lib and WEB-INF/lib.
LinkageError: loader constraint violation Two loaders disagree about the same type in a method signature.
java.lang.NoSuchMethodError A different version of a library won, usually the one in lib shadowing yours (or the reverse).
javax.servlet / jakarta.servlet missing Wrong Tomcat line for your namespace (versions).

Simulating the delegation rules

The stand-in below models loaders as a chain of "class tables" and applies the rules: JDK classes always from the top, servlet API from Tomcat, everything else web-app first. Change the data to reproduce a duplicate-JAR problem.

Java Which loader provides the class? (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at com.google.gson.Gson: it exists in both common and the webapp, and the web app's own copy wins. If it appeared in common only, your code would use it too. If a framework in lib expected its Gson and received a different version through your app, you get NoSuchMethodError or ClassCastException.

Seeing the real chain

In a running application you can print who loaded what. Read-only snippet for a servlet or a test page:

Java
ClassLoader cl = getClass().getClassLoader();
while (cl != null) {
    log(cl.getClass().getName() + " -> " + cl);
    cl = cl.getParent();
}
// typical: org.apache.catalina.loader.ParallelWebappClassLoader
//          jdk.internal.loader.ClassLoaders$AppClassLoader
//          jdk.internal.loader.ClassLoaders$PlatformClassLoader

(The common loader appears as a URLClassLoader-like instance in the chain; exact class names vary with Java and Tomcat versions.)

The same plain Java idea works on any JVM. This program walks the loader chain of a class and shows where String and your own class come from:

Java Walk the class loader chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Class loader leaks

When an application stops or reloads, its loader should become unreachable and be garbage collected together with every class it loaded. A leak means something outside the app keeps a reference into it, so the loader and all its classes stay in memory (Metaspace). Classic causes:

  • A JDBC driver in WEB-INF/lib registered with DriverManager (a shared, JVM-wide registry) and never deregistered.
  • A thread started by the app (or a thread pool) that is not stopped.
  • ThreadLocal values left on container threads (worker threads outlive the app).
  • Static caches in libraries placed in lib that hold app objects.
  • Shutdown hooks and timers.

Tomcat fights back with the JreMemoryLeakPreventionListener and the WebappClassLoader itself, which on stop logs warnings such as The web application [shop] appears to have started a thread named [Timer-0] but has failed to stop it. Treat those warnings seriously, and implement a ServletContextListener.contextDestroyed that stops your threads and deregisters drivers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In what order does the webapp class loader search for a normal application class?

    Tomcat's webapp loader is parent-last for application classes, which gives each app its own library versions. JRE and servlet API classes still come from the parent.
  2. 2. Which classes can a web application NOT override with its own copy?

    JRE classes and the container's Servlet/JSP/EL/WebSocket API must be shared, so they are always loaded from the parent.
  3. 3. You see ClassCastException: com.acme.Foo cannot be cast to com.acme.Foo. What is the most likely cause?

    A class is identified by name plus loader. Two copies of the JAR in different places produce two incompatible types.
  4. 4. Which is a common cause of a class loader leak after redeploying?

    A running thread keeps a reference to application classes through its stack, so the loader cannot be collected.

Summary

  • Tomcat's loaders: bootstrap, system, common (lib) and one webapp loader per context.
  • Webapp loaders look in WEB-INF/classes and WEB-INF/lib first, except for JRE and servlet API classes.
  • Put application JARs in the WAR; use lib only for what the container itself must see (for example a JDBC driver for a container-managed pool).
  • Duplicate libraries cause ClassCastException and NoSuchMethodError.
  • Stop threads and deregister drivers on shutdown to avoid class loader leaks.

Next: The Manager app and parallel deployment