Friday, January 17, 2014

Double checked locking optimization

Double checked locking aims to improve performance by reducing the need to acquire a lock by checking for the locking criteria first without acquiring the lock. Subsequently, if the lock is acquired, the locking criteria is checked again in order to ensure thread-safe code.

The locking criterion variable needs to be volatile for this to work correctly. If it not volatile, the compiler might optimize access to the variable thus allowing for it to contain an older value when the locking criterion check is made.

This technique is generally used in Singleton definition.

Example
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;  
  
  private MySingleton() {
  }

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

No comments: