Tomcat classloader violates delegation policy

  • Question1: As you know, when a class loader loads a class, it delegates the request to its parent class loader. However, this is not the case in Tomcat: you can load your class to overwrite the same class of names that is placed in the shared lib directory. This means that Tomcat WebappClassloader does not comply with the delegation policy. Is this a violation of the convention?

  • Question2: I wrote a class and placed it in the shared lib directory, it is obvious that the class is shared between web applications. For example, each web application can read / write a static field of a class. In addition, classes in the JDK are loaded by the Bootstrap class loader, then their static fields are shared by any web applications, is this dangerous?

+4
source share
1 answer

This behavior is intentional, and it allows you to redefine the libraries provided in Tomcat independently independently of each WAR. For example, you can override Log4J with a different version for each application deployed in the container without any problems or disruption to other applications. From Tomcat documentation :

Like many server applications, Tomcat installs many cool [...] downloaders to allow different parts of the container, and web applications running on the container have access to various repositories of available classes and resources . This mechanism is used to provide the functionality defined in the servlet specification, version 2.4 - in particular in sections 9.4 and 9.6.

It violates the usual delegation algorithm, but another application server (for example, JBoss) also works like this.

Ad. question 2 : Yes, it is dangerous, you have to remember about synchronization and you can’t control who changes this variable. I would generally avoid static fields.

For example, EhCache allows you to share CacheManager . This is done through the net.sf.ehcache.CacheManager#singleton static volatile field. Now you are having problems: if you put ehcache.jar in Tomcat /lib , it will work as expected. However, if each web application has its own copy of the JAR file, sharing will not work because each web application has its own copy of the CacheManager class. This gets even worse when only one application has its own ehcache.jar - all applications will use the same CachedManager instance, except for one that has ehcache.jar packaged together. Such an error is very difficult to track ...

+6
source

All Articles