In Java, a singleton class is a class that can have only one instance at a given time. It is one of the five Creational Design patterns in Java which helps in effortless development of Java programs. Through the medium of this article, I will give you clear insights into what is a singleton class in Java and how you can create it.
Below are the topics I will be covering in this article:
Let’s get started.
What is a Singleton Class in Java?
In layman terms, a Singleton class in Java is the class which allows access to it through a single instance at a time. This design pattern is for restricting the unnecessary instantiation of a class and ensuring that only one object of the class exists at any point of time per JVM instance. Thus, with this pattern, any class that is defined as Singleton has only a single instance with a global point of access to it. Unlike normal classes, a singleton class is not destroyed by the end of the applications life cycle.
But why do we need a Singleton Class in the first place?
Well, by restricting the instance creation of a class it saves memory space as now the object won’t be created each time a new request is made. Instead, a single object will be used repeatedly. This is the reason the Singleton pattern in Java is mostly used with multi-threaded and database applications. It is basically used for logging, caching, thread pooling, configuration settings and many more.
I hope you are clear with the concept of Singleton class in Java. So, lets now proceed further in this Singleton Class in Java article and see how they are created.
Ways to Design a Java Singleton Class
In order to make a class singleton in Java, you need the following three things:
- static member of a class
- private constructor
- static factory method
Since Java lets the developers explore their horizons, there are a number of ways in which you can design a Singleton class. Below I have listed down the most popular ones.
- Eager Initialization Method
- Lazy Initialization Method
- Thread Safe Singleton Method
- Lazy Initialization with Double Lock Method
- Lazy Load Method
- Static Block Initialization Method
Elevate your web development skills with our industry-relevant Node JS Certification program and stay ahead in the ever-evolving tech world.
Let’s now dive deeper into each of these approaches one by one.
1. Eager Initialization Method
This is the easiest method of creating a Singleton class where the instance is created at the time of class loading. To create a singleton class using this method, you need to follow the below-mentioned steps:
- Declare the constructor private.
- Next step is to create a private class member for this Singleton class.
- Now, you need to define a factory method which will be used to return the object of your class, that we have created as an instance of the class member.
- You can even declare a static member public if you want to access this static instance directly.
Now, let’s see how to implement these.
//Eager Initialization public class EagerSingleton { private static final EagerSingleton INSTANCE = new EagerSingleton(); private EagerSingleton() {} public static EagerSingleton getInstance() { return INSTANCE; } }
If you see the code, you can observe that each time we are instantiating an object we are making use of the getInstance()method rather than invoking the class constructor. But it has its own disadvantages. If you use this method to make a class singleton, then an instance would be created irrespective of the fact whether the application is using it or not.
So, let’s move ahead and see another way of creating a singleton class in Java.
2. Lazy Initialization Method
This method is called lazy initialization because it postpones the creation of the class instance until its first use. What I mean is, with this method, an object is created only if it is needed. It helps in avoiding unnecessary creation of the class instance. To design a singleton class in this way, you need to follow the below-listed steps:
- First of all, declare the constructor as private.
- Then you need to create a private static instance for this class but no need to instantiate it yet.
- Finally, create a factory method that will first check whether the instance member is null or not. If not then it will create an instance of the singleton class for you and return it.
Below code shows how to perform this.
//Lazy Initialization public class LazySingleton { private static LazySingleton INSTANCE = null; private LazySingleton() {} public static LazySingleton getInstance() { if (INSTANCE == null) { synchronized(LazySingleton.class) { INSTANCE = new LazySingleton(); } } return INSTANCE; } }
3. Thread Safe Singleton Method
But the above approach can raise some concerns in the concurrent scenarios. Since singleton pattern is mainly used with multi-threads and if multiple threads enter the if condition at the same time it can raise issues. To avoid this we try to create a thread-safe singleton class by making the global access method synchronized. This ensures that only one thread is executing this method at any point in time. Refer to the below code to see the implementation:
//Thread Safe Singleton public class ThreadSafeSingleton { private static ThreadSafeSingleton INSTANCE; private ThreadSafeSingleton(){} public static synchronized ThreadSafeSingleton getInstance(){ if(INSTANCE == null){ INSTANCE = new ThreadSafeSingleton(); } return INSTANCE; } }
But at times this approach can also become very cumbersome as each time the method is invoked it needs to wait for the lock to gets released before the method can use it. This results in slowing down the process and leading us to the next approach that is Lazy Initialization with Double Lock.
4. Lazy Initialization with Double Lock Method
In this approach, we do not synchronize the methods. Rather we envelop the object creation code within a synchronized block. You can say that by checking the thread locks beforehand, it reduces the number of lock acquisitions. This approach usually results in boosting up the performance of the application. Check out the below code to see how it is done.
//Lazy Initialization with Double Lock public class LazyDoubleLockSingleton { private static LazyDoubleLockSingleton INSTANCE = null; private LazyDoubleLockSingleton() {} public static LazyDoubleLockSingleton getInstance() { if (INSTANCE == null) { synchronized (LazyDoubleLockSingleton.class) { if (INSTANCE == null) { INSTANCE = new LazyDoubleLockSingleton(); } } } return INSTANCE; } }
5. Lazy Load Method
This method is based on JSL(Java Language Specification) and according to this JVM will load static data members only when they are required. Thus when your singleton class is loaded into the JVM, no instance is created. Further, during the execution of the program, the global method is invoked in sequential order. With this method, you don’t have to explicitly synchronize the static getInstance() to load and initialize. The static class member will be invoked in a proper sequenced manner, rest of concurrent invocations of the global method are returned in the same order without having to perform the synchronization overhead.
Below is the code to perform the same.
//Lazy Load Method public class LazyLoadSingleton { private LazyLoadSingleton() {} private static class SingletonClassHolder { static final Var INSTANCE = new LazyLoadSingleton(); } public static LazyLoadSingleton getInstance() { return SingletonClassHolder.INSTANCE; } }
6. Static Block Initialization Method
This method of creating a singleton class in Java is similar to eager initialization method. The only difference is that the instance for this class is created within the static block having exception handling functionality.
//Static Block Initialization public class StaticBlockSingleton { private static StaticBlockSingleton INSTANCE; private StaticBlockSingleton(){} //exception handling within static block static{ try{ INSTANCE = new StaticBlockSingleton(); } catch (Exception e) { throw new RuntimeException("Exception occured while creating a Singleton Class"); } } public static StaticBlockSingleton getInstance(){ return INSTANCE; } }
This brings us to the end of this article on Singleton class in Java. If you want to know more about Java you can refer to our other Java Blogs.
Elevate your coding skills to new heights with our dynamic Full Stack Development Course.
Now that you have understood what is a Singleton class in Java, check out the Java Certification Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this “Singleton Class in Java” article and we will get back to you as soon as possible.