-
Question1:
As we know, when a classloader is about to load a class, it delegates the request to its parent classloader. However in Tomcat, it doesn’t: you could load your class to overwrite the same name class which is put in common lib directory. This means TomcatWebappClassloaderdoesn’t follow delegating policy. Is it violation of convention? -
Question2:
I wrote a class and put it in common lib directory, obviously the class is shared among web apps. For instance, every web app can read/write the static field of the class. Further, classes in JDK are loaded by Bootstrap classloader, then their static fields are shared by any web apps, is it dangerous?
Question1: As we know, when a classloader is about to load a class, it
Share
This behavior is intentional and it allows you to override libraries provided in the Tomcat itself independently in every WAR. For instance you can override Log4J with different version per each application deployed to the container without introducing any issues or breaking other applications. From Tomcat documentation:
It does violate the normal delegation algorithm, but this is how other application server work as well (JBoss for instance).
Ad. question 2: Yes, it is dangerous, you have to remember about synchronization and have no control over who modifies this variable. I would avoid
staticfields altogether.For instance EhCache allows you to share
CacheManager. This is implemented vianet.sf.ehcache.CacheManager#singletonstatic volatilefield. Now you get all sort of problems: if you putehcache.jarin Tomcat’s/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 app has its own copy ofCacheManagerclass. It gets even worse when only one application has its ownehcache.jar– all applications will share the same instance ofCachedManagerexcept the one havingehcache.jarpackaged together. Such error are very hard to track down…