Java Design Patterns Singleton Patterns thread safe via "Eager initialization"

Introduction

Use "Eager initialization" to achieve thread safety.

In this solution an object of the singleton class is always instantiated.

Example

class ConfigurationManager {
   // Early initialization
   private static ConfigurationManager instance = new ConfigurationManager();

   // make the constructor private to prevent the use of "new"
   private ConfigurationManager() {
   }//from w  w w  . ja v a2  s  .  c  o  m

   // Global point of access 
   public static ConfigurationManager get() {
      return instance;
   }
}

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