Wednesday, February 19, 2014

Synchronized block


Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then Java synchronized block will throw a NullPointerException.

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

No comments:

Post a Comment