title: Java: Lazy Initializing Singleton
body: <p>The pattern to create singletons seems to be something like:</p>
  
  <pre><code>public class Singleton {
      private static final Singleton instance = new Singleton();
      private Singleton(){
      }
  
      public static Singleton getInstance()
      {
          return instance;
      }
  }
  </code></pre>
  
  <p>However my problem is how do you Unit with a class like this if the Singleton Constructor does something that is not unit test friendly e.g. calls external service , jndi lookup etc. </p>
  
  <p>I would think i could refactor it like:</p>
  
  <pre><code>public class Singleton {
      private static Singleton instance;
      private Singleton(){
      }
  
      public synchronized static Singleton getInstance()
      {
          if(instance == null)
               instance = new Singleton();
          return instance;
      }
  
       //for the unit tests
       public static void setInstance(Singleton s)
       {
            instancce = s;
       }
  }
  </code></pre>
  
  <p>The problem now is that just for unit testability I have forced the getInstance to be synchronized so just for testing aspect it will have a negative impact on the real application. Is there a way around it, it seems any other sort of lazy initialization will not work because of the broken nature of double locking pattern in java.</p>