Singleton Class In Java or Singleton Design Pattern is mostly asked in java interviews. In this article we will explain whats Singleton Design Pattern and how to write Singleton Class In Java with some examples. The main purpose of Singleton Design Pattern is to ensure single instance of a class (this class is also called Singleton class) at all the time.The Singleton pattern’s intent is to ensure that a class has only one instance and provides a global point of access to it. It ensures that all objects that use an instance of this class are using the same instance.
♦For Singleton class we can not create more than one instance at any cost. Really?
♦So how to restrict a class not to have many instances?
♦What makes a class Singleton?
♦All the above questions will be clear. Lets have a short assessment before jumping into the real topic…
1. I have a class say its SampleClass. So how to create an object of this class? Any body can answer it. Its simply
new SampleClass();
2. Can we create another object of the class? Of course yes. We can create again another object the same way as above. So there is no restrictions to create objects of the class. We can always instantiate the class as many times we want provided the class is public.
3. Just to brush up core java. Can we have private class? Only inner class can be a private. Even in the inner class we can instantiate a private class.
4. Lets design SampleClass like
package com.proliferay.design.pattern; public class SampleClass { // Private Constructor private SampleClass() { } }
5. We just added private constructor. There is no doubt, private constructors are allowed in java. Now how to create the object of SampleClass? We can not create any object by new SampleClass() in different class. For example
package com.proliferay.design.pattern; class AnotherClass { // We can not create object of SampleClass like this SampleClass sampleClass = new SampleClass(); }
6. But inside of SampleClass we still can create object like this
package com.proliferay.design.pattern; public class SampleClass { // Private Constructor private SampleClass() { } public void anyMthod() { // No problem to call private constructor SampleClass sampleClass = new SampleClass(); } }
7. Can we create an instance of SampleClass and let the other class use it whenever needed. Its possible. Lets redesign the SampleClass
package com.proliferay.design.pattern; public class SampleClass { // Private Constructor private SampleClass() { } public static SampleClass getInstance() { SampleClass sampleClass = new SampleClass(); return sampleClass; } }
8. Now any class can call getInstance() method like SampleClass.getInstance(). No need to create any object to call the method. Every time giving a call to getInstance() will return a fresh object of SampleClass. Can we control it? Obviously yes. Lets give a final touch
package com.proliferay.design.pattern; public class SampleClass { private static SampleClass instance; // Private Constructor private SampleClass() { } /** * * Before returning the instance check its null or not. If not null return * the same instance otherwise make a fresh one and return */ public static SampleClass getInstance() { if (instance == null) { instance = new SampleClass(); } return instance; } }
9. But still something missing. If the above code is running in multi threaded environment then we may have multiple instance of the class. So to take care of it use synchronized keyword. So the final code will look like
package com.proliferay.design.pattern; public class SampleClass { private static SampleClass instance; // Private Constructor private SampleClass() { } /** * * Before returning the instance check its null or not. If not null return * the same instance otherwise make a fresh one and return */ public static synchronized SampleClass getInstance() { if (instance == null) { instance = new SampleClass(); } return instance; } }
Now the class SampleClass is perfect Singleton class. That means it returns only one instance. So for Singleton class in java only 2 main points
Point 1: Private Constructor.
Point 2: Global point of access like getInstance() method.
Q. Can we have singleton accross JVM?
A:It depends. Consider we have developed one web application with Singleton Class. If the web application is deployed in the tomcat multiple times with different context then the Singleton Class will have multiple instances both in different context. Because each context has its own ClasLoader. In other words we can say that Singleton Class is associated with ClassLoader. So in one JVM we can have multiple instances of a Singleton Class.
But if the Singleton Class is deployed in the shared lib of the tomcat then it will have only one instance across the JVM.
Q. Whats Lazy and Early Loading of Singleton Class?
A: The Singleton class shown in the above is Lazy Singleton Class. That means we will get the instance of the Singleton Class only when we call getInstance() method. But early loading of Singleton class is also possible by using static block. For example
package com.proliferay.design.pattern; /** * * @author Hamidul Islam * */ public class EarlyLoadingSingleton { /** * Final variable can be assigned only one time Therefore final keyword is * used here to ensure only one instance of the class */ private static final EarlyLoadingSingleton instance; /** * This block will be executed first when the class is loaded Before the * class is used by any thread */ static { try { System.out.println("Creating Instance...."); instance = new EarlyLoadingSingleton(); System.out.println("Instance Created."); } catch (Exception e) { throw new RuntimeException("Hey something wrong!", e); } } private EarlyLoadingSingleton() { } /** * * No need of using synchronized keyword here. That means all the thread * will see the same instance. No expensive locking is needed */ public static EarlyLoadingSingleton getInstance() { return instance; } }
Q. May I know any one Singleton Class in Java SE API?
A: Yes. One of the API associated with Singleton Pattern is java.lang.Runtime.
Pingback: Design Patterns In Java - Pro Liferay