Singleton across JVM or Application instance or Tomcat instance
It is possible to create such a singleton by assuring that you always query the same ClassLoader
for the singleton. I wrote an extensive explanation in this other answer.
If you have a singleton class and you run two webapps that use this class in Tomcat both webapps will get 2 different instances of this singleton in JVM running the Tomcat.
But if your webapp will use a singleton from JRE or Tomcat shared libs, eg Runtime.getRuntime webapps will get the same instance of Runtime.
This is because Tomcat uses individual class loaders for webapps. When a webapp class loader loads a class it first tries to find it on webapp class path, if the class is not found it asks parent class loader to load the class.
A singleton is normally tied to a ClassLoader
only.
So if you have a singleton based on a .class file in your .war file, and you deploy this web application multiple times, each application gets its own singleton.
On the other hand, if the .class file of your singleton is in the classpath of tomcat
, then you only have one instance. This .class does not belong to a specific web application (it belongs to the tomcat
instance).
If you have the singleton in both locations, it depends on the class loader hierarchy, and you can possibly select between "parent first" or "web application first".
- The Tomcat creates new class loader for each web application.
- So if your Singleton class is stored in war file, the same war file will have two instances in Tomcat container i.e. it creates two separate Singleton class for each war file.
- If the Singleton class is in Tomcat's share library path, Tomcat creates only one Singleton instance for the both application.
JVM analogy:
JVM is like big mansion. It contains combined family with serveral applicance and libraries.
ClassLoaders are family members, each family member represents one ClassLoader (works as delegate hierarchy not inheritance hierarchy). Note: ClassLoader is class, it can create multiple instances.
Applications are like appliance. for example: Washing Machine, Fridge, Air Cooler, Television, Dining table, Sofa and so on...
Libraries are each one having his own individual library. Every one search in parent's library if not found then search in his own library.
limitations: If father buy an appliance their children can use it, but it can not used by his parent and siblings. Each application might use different versions of the same libraries. i.e. If library contain two or more versions of same books, it picks whichever the book is available first.
Each family number can use only one unique appliance.
In home, we can use multiple appliance of same version. So, JVM allows us to run multiple applications of same versions.
Garbage Collector is a servant in Mansion, who roams as a daemon, who can clear any kind of Objects.
The scope of a static variable is limited to one per ClassLoader.