Singleton Class in Java
In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined.
Remember the key points while defining class as a singleton class that is while designing a singleton class:
- Make a constructor private.
- Write a static method that has the return type object of this singleton class. Here, the concept of Lazy initialization is used to write this static method.
Purpose of Singleton Class
The primary purpose of a Singleton class is to restrict the limit of the number of object creation to only one. This often ensures that there is access control to resources, for example, socket or database connection.
The memory space wastage does not occur with the use of the singleton class because it restricts the instance creation. As the object creation will take place only once instead of creating it each time a new request is made.
We can use this single object repeatedly as per the requirements. This is the reason why the multi-threaded and database applications mostly make use of the Singleton pattern in Java for caching, logging, thread pooling, configuration settings, and much more.
For example, there is a license with us, and we have only one database connection or suppose if our JDBC driver does not allow us to do multithreading, then Singleton class comes into the picture and makes sure that at a time, only a single connection or a single thread can access the connection.
How to Design/Create a Singleton Class in Java?
To create a singleton class, we must follow the steps, given below:
1. Ensure that only one instance of the class exists.
2. Provide global access to that instance by
- Declaring all constructors of the class to be private.
- Providing a static method that returns a reference to the instance. The lazy initialization concept is used to write the static methods.
- The instance is stored as a private static variable.
Example of singleton classes is Runtime class, Action Servlet, Service Locator. Private constructors and factory methods are also an example of the singleton class.
Difference between Normal Class and Singleton Class
We can distinguish a Singleton class from the usual classes with respect to the process of instantiating the object of the class. To instantiate a normal class, we use a java constructor. On the other hand, to instantiate a singleton class, we use the getInstance() method.
The other difference is that a normal class vanishes at the end of the lifecycle of the application while the singleton class does not destroy with the completion of an application.
Forms of Singleton Class Pattern
There are two forms of singleton design pattern, which are:
- Early Instantiation: The object creation takes place at the load time.
- Lazy Instantiation: The object creation is done according to the requirement.
Implementation: Let us brief how the singleton class varies from the normal class in java. Here the difference is in terms of instantiation as for normal class we use constructor, whereas for singleton class we use getInstance() method which we will be peeking out in example 1 as depicted below. In general, in order to avoid confusion, we may also use the class name as method name while defining this method which will be as depicted in example 2 below as follows.
Hashcode of x is 558638686 Hashcode of y is 558638686 Hashcode of z is 558638686 Three objects point to the same memory location on the heap i.e, to the same object
In a singleton class, when we first-time call the getInstance() method, it creates an object of the class with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time, if we try to call the getInstance() method since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again. This part is done by if condition.
In the main class, we instantiate the singleton class with 3 objects x, y, z by calling the static method getInstance(). But actually, after the creation of object x, variables y and z are pointed to object x as shown in the diagram. Hence, if we change the variables of object x, that is reflected when we access the variables of objects y and z. Also if we change the variables of object z, that is reflected when we access the variables of objects x and y.
Now we are done with covering all aspects of example 1 and have implemented the same, now we will be implementing Singleton class with method name as that of the class name.
String from x is HELLO I AM A STRING PART OF SINGLETON CLASS String from y is HELLO I AM A STRING PART OF SINGLETON CLASS String from z is HELLO I AM A STRING PART OF SINGLETON CLASS String from x is hello i am a string part of singleton class String from y is hello i am a string part of singleton class String from z is hello i am a string part of singleton class
Output explanation: In the singleton class, when we first time call Singleton() method, it creates an object of class Singleton with the name single_instance and returns it to the variable. Since single_instance is static, it is changed from null to some object. Next time if we try to call Singleton() method, since single_instance is not null, it is returned to the variable, instead of instantiating the Singleton class again.
This article is contributed by Pavan Gopal Rayapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.