Singleton and Class Loaders in Tomcat Web Applications

I did a lot of research on the Internet, but I can’t find a final answer to my question, so I turned to the experts on this site.

When developing using java and Tomcat, I have a Singleton class that handles my database connection. So the question is, when do different users connect to my web application and my server side Java code executes its own single class?

For example:
User A is registered on my site. An instance of my singleton is created.
User B is registered on my site, is the same object (singleton) saved between two versions of java code? or each performance for user A and user B receive different singletones?

thank.

+3
source share
2 answers

Syntax means one instance per JVM (for each classloader, to be precise). Tomcat does not have a separate environment for each user. Instead, it has a separate class loader (and therefore a separate environment) for each web application. Therefore, no matter how many users are connected, the server side is a single environment, and this environment has one instance of your singleton class, which is shared by all classes loaded into this environment.

0
source

The syntax stored in the static field is unique to each class loader. Thus, all users of your web application on the tomcat instance will use the same singleton.

+5

All Articles