Singleton Pattern – Design Patterns in Java/J2EE

SHARE & COMMENT :

Situations often will demand for the existence of only one object for a particular class in an Application. For example, the existence of only one Database Connection for a particular session, one object referencing the set of Global properties being shared across the various modules, etc. Such classes are candidates to be designated as Singleton classes. The sole purpose of such a class is to ensure that only one instance of the class is created for the entire Application and that instance is shared across multiple clients.

also read:

So, how to make a class to behave as a Singleton class? For example, let us consider the class, say MyConnection, which we wish to make as a Singleton class. Given below is the class definition,
MyConnection.java

package tips.pattern.singleton;

public class MyConnection {
    private static MyConnection connection = new MyConnection();

    private MyConnection() {
    }

    public static MyConnection getConnection() {
        return connection;
    }
}

Note that we have declared a static object called connection which is of type MyConnection. Also note that declaration of the private constructor which tells that no other outside classes can directly instantiate this class. The only way to get a reference to the MyConnection object is to make a call to the static method MyConnection.getConnection().
What happens if the client calls MyConnection.getConnection() multiple times? Since the connection object is maintained as a static object, multiple calls to MyConnection.getConnection() will return a reference pointing to the same object. This can be proven by the following code,
MyConnectionConsumer.java

package tips.pattern.singleton;

public class MyConnectionConsumer {
	public static void main(String[] args) {
		MyConnection connection1 = MyConnection.getConnection();
		MyConnection connection2 = MyConnection.getConnection();
		if (connection1 == connection2) {
			System.out
					.println("Both the references are pointing to the same object");
		} else {
			System.out.println("Objects are not equal");
		}
	}
}

The output of the above program will be “Both the references are pointing to the same object”. There is one major flaw in our singleton class declaration. What if the client doesn’t use the MyConnection class? Since the connection object is maintained as a static object, the object will be loaded during the time of MyConnection class loading itself. So, let us prevent this by making the following changes,
MyConnection.java

package tips.pattern.singleton;

public class MyConnection {
	private static MyConnection connection = null;

	private MyConnection() {
	}

	public static MyConnection getConnection() {
		initObject();
		return connection;
	}

	private static void initObject() {
		if (connection == null) {
			connection = new MyConnection();
		}
	}
}

Two well-known changes are noted in the code. One is the static object connection is not initialized in the declaration itself. The second change is the introduction of the new method initObject() which gets called whenever a clients request for the Objecr by calling MyConnection.getConnection(). The method initObject() creates a new object for the very first time only by making a comparison check.
Will the class works well in a multi-threaded environment? Certainly not. Why? Imagine two threads trying to access the MyConnection.getConnection() method. So, it is always wise to synchronize the object creation logic in the implementation. So the final revised code looks similar to this.

 private static void initObject(){
	 synchronized (MyConnection.class) {
		 if (connection == null){
			 connection = new MyConnection();
			}
	}
}

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Thanks a lot. Was really useful info

  2. This design pattern is used for controlling the number of instances of a class (to one in general). This is maybe the first, the most used and the easiest design pattern out there.
    Beware that this control ( controlling the number of instances of a class ) is available per classloader, and not for JVM, not to say more when thinking at distributed topologies. This is because the final static instance variable – being static is per class basis. As you know now, in a JVM you can have more than one classloader – meaning you can load the same Singleton implementing class more than once (once per classloader). Loading more than once the Singleton implementing class results in the possibility of having n instances controlled by the singleton per JVM, where n represents the number of the loads of the Singleton implementing class, so will need at least n classloaders.
    In a multiple JVM topology ( cluster deployed application ) special algorithms must be taken into consideration for controlling the number of instances of a class. These can be fine-tuned depending on the needs of the application requirements.
    The Singleton design pattern can also be expressed as an eager implementation which is thread safe too. Using synchronized you can make it thread safe without the eager initialization.
    More at:
    http://centraladvisor.com/programming-2/design-patterns/what-is-singleton-pattern

    B/

  3. kanishka says:

    Nice article

Trackbacks

  1. […] an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as […]

  2. […] Singleton : Used when desired, that a class has only one instance of the application. Below are some aspects that should be taken care of when creating this pattern: […]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better