Thursday, November 4, 2010

Singleton Design Pattern

Singleton Pattern Flavors: Check out some Singleton Design Pattern flavors.

1: Simplest: Early Initialization

public class SimpleSingleton {
 private static final SimpleSingleton instance = new SimpleSingleton();

 private SimpleSingleton() {
 }
 public static SimpleSingleton getInstance() {
  return instance;
 }
}


2: Lazy Initialization with improved performance but does not guarantee for single object per JVM.

Reason: Think about a multithreaded environment where two threads try to call getInstance method first time. Thread one check that instace is equal to null and before creating an object in next line it suspends and second thread get a chance to run this method. Second thread comes and see that instance is null and creates an object and returns object. Now first suspended thread starts again and since it has already checked that instance was null it again create a new object and returns. So it does not guarantee for one object per jvm.

 public class SimpleSingleton {
 private static SimpleSingleton instance = null;

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


3: Lazy Initialization at cost of poor performance:

public class SimpleSingleton {
 private static SimpleSingleton instance = null;

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


4: Singleton with improved performence and guarantees single object per JVM with double checking mechanism.  

public class SimpleSingleton {
 private static SimpleSingleton instance = null;

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

No comments:

Post a Comment