In doubt DCL solution

Brad Abrams posted a double checked locking algorithm which does not use volatile at http://blogs.msdn.com/brada/archive/2004/05/12/130935.aspx.

Unfortunately, however, his idea is in doubt because of possible reording in reader threads.

I think the today’s design guide line, posted by him, is better and safe way. The guide line is as follows:


public sealed class Singleton {
   private Singleton() {}
   private static volatile Singleton value;
   private static object syncRoot = new Object();
 
   public static Singleton Value {
      get {
         if (Singleton.value == null) {
            lock (syncRoot) {
                if (Singleton.value == null) {
                    Singleton.value = new Singleton();
                }
            }
         }
         
         return Singleton.value;
      }
   }      
}

Initialization on demand idiom is an attractive alternative to above code.


private static class LazySomethingHolder {
  public static Something something = new Something();
}

public static Something getInstance() {
  return LazySomethingHolder.something;
}

Here’s the conclusion.

1. If you use .NET or JDK 1.5 or higher, you can use volatile based DCL.
2. If you use JDK 1.4 or lower, you must use ‘Initialize on Demand Idiom.’
3. DO NOT TRY TO DEVISE A WORKAROUND FOR DOUBLE CHECKED-LOCKING. (However, studying what DCL will definitely provide you with lots of information about threading.)

I recommend the initialize on demand idiom.

Similar Posts:

Post a Comment

Your email is never published nor shared.