Java Design Patterns Singleton Patterns thread safe via "synchronized" keyword

Introduction

There is a performance cost associated with this synchronization method.

Example

class ConfigurationManager {
   private ConfigurationManager() {
   }/*from  w  w  w  .j  av  a2  s .  c om*/

   private static class SingletonHelper {
      private static final ConfigurationManager intance = new ConfigurationManager();
   }

   //Use of "synchronized" keyword
   public static synchronized ConfigurationManager get() {
      return SingletonHelper.intance;
   }

}

public class Main {
   public static void main(String[] args) {
      ConfigurationManager c1 = ConfigurationManager.get();
      ConfigurationManager c2 = ConfigurationManager.get();
      if (c1 == c2) {
         System.out.println("c1 and c2 are same instance");
      }

   }
}



PreviousNext

Related