Search code examples
javamysqltomcatclassloader

Singletons and class loaders in Tomcat web applications


I have been doing a lot of research online but can't seem to find a definitive answer to my question which is why I turned to the experts on this site.

When developing with java and Tomcat I have a Singleton class that handles my database connection. So the question is when different users connect to my web application, and my server side java code executes does it get its own singleton class?

For example:
User A logs into my site. An instance of my singleton is created.
User B logs into my site, does the same object (singleton) persist between the two executions of the java code? or is each execution for user A and user B get different singletons?

thank you.


Solution

  • A singleton means a single instance per JVM (per classloader, to be precise). Tomcat does not have seperate environment per user. Instead, it has seperate classloader (and hence separate environment) per web application. Hence, no matter how many users are connected the server side is a single environment and this environment has a single instance of your singleton class which is shared by all the classes loaded in that environment.