title: Singleton pattern with combination of lazy loading and thread safety
body: <p>I was doing some research about singletons, specifically regarding lazy vs eager initialization of singletons.</p>
  
  <p>An example of eager initialization:</p>
  
  <pre><code>public class Singleton
  {
      //initialzed during class loading
      private static final Singleton INSTANCE = new Singleton();
  
      //to prevent creating another instance of Singleton
      private Singleton(){}
  
      public static Singleton getSingleton(){
          return INSTANCE;
      }
  }
  </code></pre>
  
  <p>but as shown above that it is eager initialization and thread safety is left to jvm
  but now, I want to have this same pattern but with lazy initialization.</p>
  
  <p>so I come up with this approach: </p>
  
  <pre><code>public final class Foo {
      private static class FooLoader {
          private static final Foo INSTANCE = new Foo();
      }
      private Foo() {
          if (FooLoader.INSTANCE != null) {
              throw new IllegalStateException("Already instantiated");
          }
      }
      public static Foo getInstance() {
          return FooLoader.INSTANCE;
      }
  }
  </code></pre>
  
  <p>As shown above Since the line </p>
  
  <pre><code>private static final Foo INSTANCE = new Foo(); 
  </code></pre>
  
  <p>is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.</p>
  
  <p><strong>Is this correct?</strong></p>