Thread Safe Singleton

Writing by on Saturday, 22 of December , 2007 at 2:09 pm

Here is an example of a Simple Singleton. There are 3 things to remember.

  • Create a private static instance of the singleton class.
  • The constructor must be private.
  • There must be a static method to get the “single” instance of the singleton class.
/* This is NOT Thread Safe - This is a Simple Example of a Singleton*/
public class SimpleSingleton {
    private static SimpleSingleton instance = null;    
    private SimpleSingleton () {
    }

    public static SimpleSingleton getInstance() {
        // lazily create an instance
        if (instance == null) {
            instance = new SimpleSingleton ();
        }
        return instance;
    }
}

Now here is an example of a Thread Safe Singleton achieved using the synchronized(instance). The reason for checking (instance == null) twice is so that we don’t want all threads to wait when getInstance() is called. Threads must wait only when instance is being created.

public class ThreadSafeSingleton {
    private static ThreadSafeSingleton instance = null;    

    private ThreadSafeSingleton() {
    }

    public static ThreadSafeSingleton getInstance() {
        // Threads will acquire a lock and wait ONLY if instance is NOT NULL
        if (instance == null) {
                // Only One Thread allowed at a time from this point
                synchronized (instance) {
                        if (instance == null) {
                            instance = new ThreadSafeSingleton();
                        }
                } // End of Synchronized Block
        }
        return instance;
    }
}

Another Thread Safe Singleton Example
Another way of achieving a Thread Safe Singleton without worrying about synchronization, is by instantiating the Singleton object when the CLASS gets loaded (in the static block). However, the we lose the “lazy initialization” nature of the ThreadSafeSingleton shown above.

public class Singleton {
    static {
        // This happens when the class is loaded.
        instance = new Singleton();
    }

    private static Singleton instance = null;    

    private Singleton () {
    }

    public static Singleton getInstance() {
        return instance;
    }
}

Leave a comment

Category: Interview,Java

No Comments

No comments yet.

Leave a comment

You must be logged in to post a comment.

Shivdev Kalambi's Blog

Shivdev Kalambi is a Software Development Manager, previously a Principal Software Engineer at ArcSight/HP. With over 16 years' experience in software development, he's worked on several technologies and played different roles and contributed to all phases of projects. Non-tech activies include Ping-pong, Rock Climbing and Yoga at PG, Golf, Skiing, Swimming & a beer enthusiast.