Home  >  Design Pattern

Example of Singleton Design Pattern in Java

By Arvind Rai, December 01, 2013
Singleton Design Pattern is widely used in the software application. This design pattern ensures that a given task will be performed by only one class and that class will be global access of point. So getting one and only one instance of class ensures so many purposes of the developers in different scenario. We will discuss the uses after creating our singleton class. Example of Singleton Design Pattern in Java

How to Create Singleton Class in Java

To ensure that a class can be instantiated only one time we need to do different checks while creating the singleton class. Java provides different ways to instantiate a class. We can get the object by cloning or by deserialization of the class. So while creating singleton we have to keep all these things in mind. We will go step by step.

1. Stop external class To Create Object

To stop external class for creating object of the singleton class directly, create the constructor as private.
package com.concretepage;
public class SingletonExample {
	private SingletonExample() {
        }
}
 
But we need to introduce a method to get an instance.

2. Lazy Initialization with Double Check in Singleton Design Pattern

To get at least one object, there should be a method to return the object of the same class.
package com.concretepage;
public class SingletonExample {
	private static SingletonExample singleton = null;
	private SingletonExample() {
        }
	public static SingletonExample getInstance() {
	        if (singleton == null) {
	            synchronized (SingletonExample.class) {
	                if (singleton == null) {
	                    singleton = new SingletonExample();
	                }
	            }
	        }
	        return singleton;
	}
}
 
Now we have a method that returns the instance of the class. What we are doing is we are creating an object using new keyword of the java.
Why we have synchronized it? Suppose more than one thread is accessing this class to get the instance, so we have synchronized it. But no need to synchronize complete method, only synchronize the creation part of object.
So why have we applied two if? Two if is doing double check. First if of code ensures that once the object is ready, do not create it again. It will save the other thread not to wait because of synchronized block. Second if of the code has the usability in the rare case. Suppose more than one thread has crossed first if of the code and waiting in queue. So if one thread has created the object, then other thread should not do that.
Why do we say it lazy initialization? This is because the singleton instance will be not be created until getInstance() method will be called.

3. Eager Initialization of Singleton Instance

In JVM, static variable will be loaded first in comparison to static block. We can initialize our singleton with the static variable and static block both.
package com.concretepage;
public class SingletonExample {
	private static SingletonExample singleton = new SingletonExample();
	private SingletonExample() {
        }
	public static SingletonExample getInstance() {
        return singleton;
        }
}
 
Static variable is holding singleton instance.
package com.concretepage;
public class SingletonExample {
	private static SingletonExample singleton = null;
	static{
		singleton = new SingletonExample();
	}
	private SingletonExample() {
        }
	public static SingletonExample getInstance() {
        return singleton;
        }
}
 
Inside static block, singleton instance has been initialized. And getInstance() method is returning the created singleton object. Why do we call it Eager initialization of singleton instance? This is because the object of singleton has been initialized when the application is starting itself.

4. Bill Pugh Singleton Class in Java

There is one more approach to initialize singleton instance that is with the help of inner static class. This approach has been suggested by the scientist Bill Pugh.
package com.concretepage;
public class SingletonExample {
	private SingletonExample() {
        }
	private static class PughSingleton { 
        public static final SingletonExample singleton = new SingletonExample();
        }
	public static SingletonExample getInstance() {
        return PughSingleton.singleton;
        }
}
 
These days Bill Pugh approach of creating singleton object is the most appreciated among the developers. The initialization of singleton object via static inner class makes it lazier than lazy initialization approach. It is also called initialization of singleton instance on demand holder idiom.

5. Stop to create Clone in Singleton Design Pattern

Now we will consider other approach by which an object can be duplicated. Cloning is one that approach which can clone an object if the class is implementing Cloneable.
package com.concretepage;
public class SingletonExample implements Cloneable {
	private SingletonExample() {
        }
	private static class PughSingleton { 
        public static final SingletonExample singleton = new SingletonExample();
        }
	public static SingletonExample getInstance() {
        return PughSingleton.singleton;
        }
	@Override
        public Object clone() throws CloneNotSupportedException {
          throw new CloneNotSupportedException();
        }
}
 
To stop it, simply override the clone() method of Cloneable interface and throw an exception. This will stop outer world not to make clone of the singleton object. But this is applicable only when if our singleton class is implementing Cloneable interface.

6. Stop to Get New Object in Deserialization via readResolve()

Serialization and deserialization is another approach by which we can get a new object of singleton. If a singleton class is implementing Serializable then it can be serialized and while deserialization it will give new instance. So what to do? We need to understand that while deserialization, readResolve method is used to create object that returns new object. So we can override it.
package com.concretepage;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SingletonExample implements Serializable  {
	private static final long serialVersionUID = 1L;
	private SingletonExample() {
        }
	private static class PughSingleton { 
        public static final SingletonExample singleton = new SingletonExample();
        }
	public static SingletonExample getInstance() {
        return PughSingleton.singleton;
        }
	private Object readResolve() throws ObjectStreamException {
        return PughSingleton.singleton;
        }
}
 
readResolve() is the method which JVM uses to instantiate of the serialized object. Override readResolve() method to return the same object. So that while deserialization, JVM will not create the new object of the singleton class.

7. Enum as Singleton in Java

Implanting enum as singleton has some advantage over cloning and serialization. Enum cannot be cloned or serialized. So if our application design is supporting enum then the requirement of singleton design pattern can be fulfilled by enum also.
package com.concretepage;
public enum SingletonExample  {
	SINGLETON;
	public void doTask (String str) {
	   //TODO
        }	
}
 

8. Complete example of Singleton Class in java

Finally, we are on the path to have a complete singleton class that fulfills the Singleton Design Pattern concept.
package com.concretepage;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SingletonExample implements Serializable, Cloneable  {
	private static final long serialVersionUID = 1L;
	private SingletonExample() {
        }
	private static class PughSingleton { 
        public static final SingletonExample singleton = new SingletonExample();
        }
	public static SingletonExample getInstance() {
        return PughSingleton.singleton;
        }
	private Object readResolve() throws ObjectStreamException {
        return PughSingleton.singleton;
        }
	@Override
        public Object clone() throws CloneNotSupportedException {
          throw new CloneNotSupportedException();
        }
}
 

Uses of Singleton Design Pattern in Java

As singleton class is global access of point, so we can use singleton design pattern when we need a global resource in our application and whose implementation is not going to changed by external class. Java uses singleton design pattern for some of its in-built classes. AWT(abstract window toolkit) is an example where classes use singleton design pattern. We can use singleton design pattern in our application in different scenario.
a. Logging By singleton Class in Java
In java for logging purpose, singleton design pattern is fit to use. The application needs a global resource to log the message so that whenever we need to change anything in the logging, it can be changed at one place.
b. Database Connection with Singleton Design Pattern
Returning connection object of database can be one more example where we should use singleton design pattern. Creating every time a database connection object is bulky for memory. If it is singleton, then application will perform better and faster.
c. Service Locator with Singleton Design Pattern
Service Locator can be another example to use singleton design pattern. Like JNDI that communicates with the resource and it must be a global access of point to maintain it.

Some Drawbacks of Singleton Design Pattern

a. The caller of singleton class does not know the implementation of singleton design pattern. Because it hides it implementation that makes singleton of lesser use.
b. No flexibility for the future to make it more than one like two or three instance.
c.Singleton class uses static class, block or variable, so no usability of making its subclass.

Alternative of Singleton Design Pattern

The complete alternative of singleton design pattern is not there but we can do something else when we feel to use singleton design pattern but not willing to use. Spring dependency injection is good example. Create the interface of the class and implementation class also and inject single instance for every component.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us