Sunday, 24 April 2016

What are the best Singleton implementations in multithreaded environment ?


IMPLEMENTATION 1. For Single thread
Typical singleton implementation works fine in Single-threaded environment, but may not in multi-threaded environment.
private static Singleton singleton;

public static Singleton getInstance() {
   if (singleton == null) {
      singleton = new Singleton();
   }
  return singleton;

}


IMPLEMENTATION 2. Synchronization with Double null checks
To be able to use it in Multi-threaded environment , use synchronized block with double null checks :
private static Singleton singleton;

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

}


IMPLEMENTATION 3. Using volatile
When the statement runs : singleton = new Singleton();
  1. It allocates memory
  2. Assign memory reference to reference variable
  3. Constructor is invoked

Here, if thread2 preempt thread1 just before invoking constructor and just after memory is allocated, it may give unpredictable results.

It may be avoided by using volatile keyword, which will ensure that each thread will get the correct value of singleton reference.
private static volatile Singleton singleton;


IMPLEMENTATION 4. Lazy initialization using static inner class
Using volatile might be slower than synchronization, so below final solution is thread-safe and does not uses either ‘volatile’ or ‘synchronization’.

private static Singleton singleton;

// Static inner class
private static class SingletonHolder {
   private final static Singleton singleton = new Singleton();
}

public static Singleton getInstance() {
   return SingletonHolder.singleton;
}

SingletonHolder is loaded on the first execution of getInstance() method - Lazy Initialization

No comments:

Post a Comment

Note: only a member of this blog may post a comment.