Singleton JAVA class | Create Singleton class in JAVA

JAVA is highly resourceful Object Oriented Programming Language. It provides support for so many concepts those are not present in other programming languages. Singleton class concept is also an important support provided by java. We can make use of a singleton Java class for different programming requirements. In JDK also there are so many predefined Singleton classes already present like Java.lang.Runtime, java.util.CalendarJava.awt.Toolkit, Java.awt.Desktop etc.





What is singleton java Class?

Singleton Classes in JAVA are specially designed classes which can have only one object. Only one instance of a Singleton java class can be created, and it returns the same object every time we try to create a new instance of this class.

In case of JAVA web-application, an object of the singleton class gets created during starting of the server(Eager initialization) or during its first user call(Lazy initialization). After that, for every user call, it returns the same object.

Factory Method: Normal java Classes use constructor for the creation of its object but the singleton classes use factory method for instantiation. Every Singleton java class has factory method which returns an object of this class. In that factory method there is logic that does not allow us to create a 2nd object of the class.

Example:

Runtime r1= Runtime.getRuntime();

Calendar c1= Calendar.getInstance();

Here we did not use ‘new’ operator to create an object of Runtime class or Calendar class. We called the static method of these classes to create an object of these singleton classes. Here getRuntime() is a factory method of Runtime Class and getInstance() is a factory method of Calendar class which return an object of these classes.

Check out : How to install Java on your Computer? Set up Environment Variable for java.

How to create Singleton Class in JAVA?

The main objective of a Singleton class is to prevent the creation of multiple objects. We can achieve that by few steps stated below.

  • Declare the constructor of the class as private so that it can not be accessed from any other class for the instantiation.
  • Write a public static method(Factory method) whose return type is the same class object.
  • Create an instance of the class only if it is not created already and return it from the factory method of this class.

Explanation: Here private constructor won’t allow creating an object by the constructor. If we try to create an object of this class from another class by  SingletonDemo sd=new SingletonDemo();, then we will get Compile time Error as “SingletonDemo() has private access in SingletonDemo“. So The only way to get an object of this class is by calling getInstance() method.




In this getInstance() method we have first checked that any object of this class is already present or not by comparing the object reference value with ‘null’. If the object reference value is equal to ‘null’ then it is clear that object reference does not hold any object. In that case, we created a new object by the private constructor and returned it. If the object reference already holds an object then the reference won’t holds the null value, so the ‘if’ statement won’t get executed and another new object will not get created and the same object will be returned to the caller.

Here this SingletonDemo class is a singleton class and it will always return the same object even though we will create it multiple time. See the class below in which we have created multiple objects references of SingletonDemo class.

See the Output of this program

So from this, we can find that both sd1 and sd2 are pointing to the same object of SingletonDemo class.

Also Check out:

Eager initialization and Lazy initialization of Singleton Class

A Singleton class can be an Eager initialization class or can be a Lazy initialization class according to the way of instantiation it does. A Singleton class may instantiate when it starts or during the class loading, or it may instantiate during first user call.

  1. If an object of a class gets created during the loading of the class then that process of initialization is called Eager Initialization. By this process, one object will be created earlier whether any user uses this object or not. If any User called the factory method then it will return that object which was created earlier.
  2. If an object of a class gets created during the 1st User call then that process of initialization is called Lazy Initialization. By this process, the object won’t get created during the loading of the class. But when a User will call the factory method a new object will be created and returned.

How to Make Singleton classes Thread Safe?

Sometimes when multiple Threads run a singleton class at a time, if two Threads will call the factory method simultaneously to get an object from it, then there is a chance that the factory method will create two objects of the singleton class. To prevent this breach we should declare the factory method as Synchronized so that only one Thread can run that method at a time.



How to access private constructor of Singleton class for instantiation

The main feature of a Singleton class is that it can have only one object. If we are creating object from the factory method of the singleton java class then we never can create more than one object of that class as it checks the instantiation.




But if we are allowed to create objects through the constructor of a class then we can create as many objects as we want. But in case of a Singleton class the constructor is private, so cannot access that from outside of the singleton class.

Apparently, there is a way in java by which we can access the private constructor of a class from outside of that class also.  It is possible only by the Reflection in Java.

There is an instance method present in java.lang.reflect.AccessibleObject class by which we can also access private constructors. That method is:

public void setAccessible(boolean) throws java.lang.SecurityException

To access the private constructor of a singleton class we have to apply this method to the private constructor by which that constructor would be accessible and then we can create multiple objects of a Singleton Class.

We can not apply setAccessible() method on a constructor directly, this method should be applied on java.lang.reflect.Constructor object. And there is a method named getDeclaredConstructord() in java.lang.Class class which returns an array of Constructor objects.

See the program below in which two different objects of a Singleton class is created.



Here two different objects are created. One by getInstance() method and another one is by accessing the private constructor. So the output will be:

From this output, we can conclude that sd1 and sd2 are two different objects of SingletonDemo class.

 

Add Comment