On a Tomcat 5.5 server, I put a class in the system classpath (and modify catalina.bat to pick it), or if I put class in the shared lib directory. Now if I have two different applications using the same class which do not have the class in their WEB-INF lib/classes directories, they use the same instance of the class. I understand the concept that a classloader will delegate to it's parent classloader for finding a class if it can't find it, so in this case, since the class is not present in the WEB-INF/classes or WEB-INF/lib the WebAppX classloader will try the shared, common and system classloader respectively.
However this somehow seems weird to me that two different applications can share a context using this method. Could someone help me understand why this is so. e.g. in below code the two servlets are each deployed in separate wars while CommonCounter is shared, and they can read the counter values incremented by the other.
Edit It appears counter intuitive to me that two separate applications can share a context in this fashion. In fact if they have the same instance of the class they can even implement multithreading/synchronization across two different applications, which seems extremely counterintuitive.
package com.test;
public class CommonCounter {
public static int servlet1;
public static int servlet2;
}
public class Servlet1 extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CommonCounter.servlet1++;
System.out.println("Other one had "+CommonCounter.servlet2+" hits");
}
}
public class Servlet2 extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
CommonCounter.servlet2++;
System.out.println("Other one had "+CommonCounter.servlet1+" hits");
}
}