Skip to content

Singleton Pattern

July 30, 2013

There are many situations that you need to have just one instance of a kind of objects, Thread pool, Cache, Registry, etc. are some examples of these situations. It is possible you ask a question: “Why do i need pattern for this problem? i can just create one object and make it global static.” . As you will see with using singleton pattern we want to be sure there is just one instance object in all of our system. We need a solution that does not let to the programmer to create more than one instance instead of programmer handle the  uniqueness of instance.

Singleton is not very complex, but has some trap points that we explain them in this post. At first let me show you what is Singleton.

In Singleton pattern we don’t let clients to create the object, So our class does not have any public ( and protected is a trap) constructor.

public class SingletonObject {
 private SingletonObject() {
}
}

no one out of your class can’t create an instance of your class. Now you need to add a static public method to retrieve your unique object.

public class SingletonObject {
 private static SingletonObject object;
private SingletonObject() {
 }
public static SingletonObject getInstance() {
 if (object == null) {
object = new SingletonObject();
}
return object;
 }
}

It is all of Singleton pattern, now you can be sure that you have just one SingletonObject instance in your application. ‌But there are two issues that you need consider them. First don’t use protected constructor in your singleton class, because everyone can extend your singleton class and add a new public constructor to it :) so you could not restrict programmers to use just one object in their applications, another possible solution is to use final keyword in your class specification.

The other issue is in concurrent environments, When your object does not initialize yet and you have two threads which want to get an instance in the same time, it is possible to have two objects of your singleton, So you need to make your object creation thread safe.

First solution is to synchronize your get Instance method.

public static synchronized SingletonObject getInstance() {
if (object == null) {
object = new SingletonObject();
}
return object;
}

Very easy and simple solution, but if you have high getInstance invocation then your application overhead will become very much. In this situation you can create your object eagerly, it’s not possible everywhere to create your object eagerly but when it is possible you have a good choice. The last solution is to use “Double-checked locking”, In this solution you check you object reference then synchronize for creating object, with this solution the overhead decrease.

public static SingletonObject getInstance() {
 if (object == null) {
 synchronized (SingletonObject.class) {
 if (object == null) {
 object = new SingletonObject();
 }
 }
 }
return object;
 }

But after release 1.5, the best way to implement Singleton pattern is using enum, with this model of implementation you don’t have any concern about the synchronization and the number of objects in your application.

public enum SingletonObject {
 INSTANCE;
public void aMethodOfSingetonOBject(){
// do something<
}
}

What do you think about enum usage? can we use this model every where?

About these ads
5 Comments
  1. Amir permalink

    Hi,
    Just wanted to mention that your “Double-checked locking” implementation is incorrect. It is NOT thread-safe for many reasons explained in detail here (http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html), unless you use “volatile” keyword in your “object” variable declaration and use JDK5 or later.

    • Yes, i missed volatile keyword and as a consequence i missed to explain it.
      Thanks for your feedback, i will edit my post today.

  2. would it be possible to Implement Singleton Design Pattern in a way which we can use it in Derived Classes ?
    imagine we have three level of Inherited Classes and All of them have been implemented with Singleton Design Pattern at the End we will have three Different Static GetInstance Method(one Method for each level) …and it’s not a good idea , is it ?
    is there anyway ?

    • Singleton classes are final (sealed in C#) so you cannot derive them. If you extend a singleton class and create an instance of it so you have two object from its base class.

      • thanks for the tip :
        “Always decorate your singleton classes with Sealed Keyword”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: