Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton across JVM or Application instance or Tomcat instance

Tags:

If I deploy and run 2 instances of same application on a single instance of Tomcat(Or any other server). Then a single object(of a Singleton class) would be created:

  1. Across single instance of Tomcat (but common for 2 instances of same application) OR
  2. Across application instance (different for 2 instances of application)

So essentially I want to understand that is it always a case that a single object of Singleton class gets created per JVM? How does this works in case of application hosted on a Web server(or container).

like image 554
Learner Avatar asked Jul 18 '13 10:07

Learner


People also ask

What is the best way to implement singleton in Java?

The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.

Can singleton class have multiple instances?

Well-designed singleton can have only one instance per application. Creating of multiple instances is a mistake in the application design. It might happen in some cases, e.g.: Non thread safe singleton with lazy initialization: several threads are trying to get an instance and creates multiple instances.

What is a singleton instance?

A singleton is a class that allows only a single instance of itself to be created and gives access to that created instance. It contains static variables that can accommodate unique and private instances of itself. It is used in scenarios when a user wants to restrict instantiation of a class to only one object.


1 Answers

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.

like image 137
Evgeniy Dorofeev Avatar answered Oct 02 '22 20:10

Evgeniy Dorofeev