Thursday, November 6, 2014

Singleton Design Pattern

The Singleton design pattern is simple and easy to understand. This pattern will ensure that only one object of a particular class is created in virtual machine. In terms of practical usage

 01).Logging 
 02).Caches 
 03).Thread pool, 
 04).Configuration Settings 
 05).Device driver objects 

 lets have a look on the very basic lazy initialization methodology of Singleton  pattern. We can test the Singleton class using following SingletonTest Class When you run the SingltonTest class the result would display as following 

Instance 1 ID :2018699554 
Instance 2 ID :2018699554 
BUILD SUCCESSFUL (total time: 1 second) 

It is very important to see the multi threading behavior on the Singleton design pattern.So lets modify the code, Create two separate classes for use the singleton instance within a thread and test the implementation within the multiple thread environment.


So, what would be the output,

Instance 1 ID :2068989547
Instance 1 ID :1793542001
BUILD SUCCESSFUL (total time: 1 second)

It is clear that the above implementation is not thread safe. There are two different Singleton instances were created in the heap. We need to have a way to overcome this situation.

It is not that hard, Simple this is where the synchronized key word is used. Lets modify the getInstance method in Singleton class. So, what would be the output, Lets see...

Instance 1 ID :1612655617
Instance 1 ID :1612655617
BUILD SUCCESSFUL (total time: 1 second)

Now we are safe. Same instance is used within the multi-threaded environment.
It is really worth to use the Singleton design pattern with the thread safe way prevent multiple instantiations.