Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
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.
In order to make a class singleton in Java, you need the following three things:
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.
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.
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:
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.
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:
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; } }
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.
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; } }
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; } }
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.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 7th December,2024 7th December SAT&SUN (Weekend Batch) | View Details |
edureka.co