Singleton Pattern

Classification: Creational Pattern
Description : Ensure a class has only one instance, and provide a global point of access to it.

Whenever I hear about Singleton ‘Forever Alone’ troll face comes to my mind 😉


In Singleton pattern, there will be only one object and wherever we want to use this class, this only object will be used. While creating this, we have to ensure that no more than one object is created for this class.

There are 3 ways of creating it :
1. Traditional way without thread safety, where constructor is made private and a public method returns reference to the only object created.
2. Thread-safe way : Double check locking
3. Thread-safe way : Using enums (this is for Java of course!)

Read about Singleton Pattern here.
The enums’ way of doing things is explained here.

The sample program in Git shows the first 2 ways. Find it here on Github

Double check locking:

In Java, we have to use ‘volatile‘ keyword. I was confused about this because the program gave the same output even if I use or not use the ‘volatile’ keyword. Then I came across this awesome blog. So according to this we have to use ‘volatile‘ whenever we use Double check locking. The problem is that compiler optimization may reorder execution orders, so that the flow of order of execution may be different from what we have written. The following can occur:
When instance = new Singleton() is called instance will be assigned the reference value of the Singleton object. But the constructor Singleton() may not be called at this point. That means instance is not fully initialized yet. So other threads that refer instance will get the partly initialized or not-yet-initialized object.


Leave a Reply

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

You are commenting using your 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