Wednesday, May 25, 2016

Tutorial on Singleton Design Pattern tutorial example java

This design pattern is used when only one instance of an object is needed throughout the lifetime of an application.The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits.

In singleton pattern trickier part is implementation and management of that single instance.
Three thing you should notice-
1) There should be only one instance allowed for a class.
2) We should allow global point of access  to that single instance.
3) Constructor should be private.

Singleton DP Implementation:

public class Singleton
{
 private static Singleton instance;
 private Singleton()
  {
  }
 public static Singleton getInstance()
 {
   if(instance==null)
      instance =new Singleton();
 }
 return instance;
}

This singleton implemented is easy to understand but there are several interesting point should be discussed.
This implementation is called Lazy Instantiation  but this implementation is not thread safe.How this is not thread safe?because this will allow multiple instances in multi threading scenario.

Let say two thread(Say Thread 1 and Thread 2) call getInstance() at the same time,two instance can be created if Thread 1 is preempted just after it enters the if block .

Making the this singleton class thread safe by doing just "synchronize" the getInstance() method thats what you were thinking? but you are wrong.How? Let see how?.

Firstly This solution is too expensive.each access to the Singletone requires acquisition of a lock but in reality we need a lock only when initializing instance and that should occur only the first time instance is called. If instance  is called n times during the course of a program run then we need the lock only for the first call.

So now to solve this problem we can synchronized the he critical code block  but this  is also not a thread safe completely.

Double-Checked Locking :

Let say Thread 1 enters the synchronized block and before it can assign the singleton member variable the thread is preempted.So another thread can enter the if block.The second thread will wait for the first thread to finish but we will still wind up with two distinct singleton instances.

So how to solve this problem?

We can do this by Double Checked Locking Mechanism.
Double checked locking is a simple trick.Let see how?.

public class Singleton
{
 private static Singleton instance;
 private Singleton()
   {
   }
 public  synchronized static Singleton getInstance()
 {
   if(instance==null)
    synchronized(Singletone.class)
    {
      instance =new Singleton();
   }
 }
 return instance;
}

This is complete Thread safe.
We can further optimize this code by Early and lazy Instantiation.How to do this?

Simply just instantiate the single instance early at the time of loading the class(early instantiation).

public class Singleton
{
 private static Singleton instance = new Singleton();
 private Singleton()
 {
 }
 public  static Singleton getInstance()
 {
   return instance;
  }
}

All the above Singletone implementation have a performance draw back.How to optimize that.lets see an example:

public class DbSingleton
{
  private static DbSingleton instance=null;
  private DbSingleton(){}
 
   public static DbSingleton getInstance()
   {
      if(instance==null)
      {
        synchronized(this)
         {
            if(instance == null)
            { 
               instance =new DbSingleton();
            }
         }
       }
        return instance;
    }
}

This is performance wise optimized also.thanks.


No comments: