In what domain is there a single instance of a Java singleton?

Tags: ,



By definition, there can be a single instance of a Java singleton class. Except of course when there’s obviously several, including the same code running on different physical machines, virtual machines, Java Virtual Machines.

Is the insurance that a JVM has a single instance of a singleton class?

In what domain is a Java singleton class unique? What relation to the notion of application, whatever the meaning of that is? What relation to the notion of process or thread in the operating system hosting the JVM? Of user connection in a web server? Does it change if we are talking Apache or Tomcat?


I design a Java class to be supplied to other software developers, which will access a remote functionality through it. That functionality is implemented redundantly on several distant machines. The class keeps a list of these machines, tracks their response time, and makes sure the requests received from its callers are sent to the currently most responsive distant machine. That’s a good use case for a singleton.

I have only a vague idea of what the other developers will call my class from. I know that’s going to be a web server, accessed by end users. I know the other software developer’s code is written in Java (because the code I replace is C and called from JNI). They talk about calling my code from several apps they make on the same machine, but I do not know what exactly that means. Definitely some run their web server on Tomcat with multiple apps in the same server. Another apparently lean towards Apache Web Server, and yet another mentioned NGINX. The less I know about what they do, the better.

I know my code will run in relatively few JVMs instances on the same machine (as shown by top), and I can live happy with that few instances of my singleton. It would be a serious issue if there was 1 singleton per end user of the web server, a mild issue is there was one per “app”. I’d like to know at the design phase, rather than discover in the field.

Answer

Usually the class loader loads only a single instance of each class into memory. So all static variables exist only once per Java VM.

But in web applications (e.g. on Apache Tomcat or similar) it’s a bit different because each application has its own class loader and there is another class loader for shared libraries.

When your Tomcat runs two applications which contain the same library (inside the *.war), you have effectively two instances of the same library in memory, so their static variables exist twice. But when two applications share a library from the lib folder, then you have only one instance in memory.

However, by implementing a custom class loader, you can alter that behavior and then it’s up to you.

Thread do not affect this normally unless you write your own class loader with specific features for threads.



Source: stackoverflow