title: Pattern for lazy thread-safe singleton instantiation in java
body: <p>the lazy thread-safe singleton instantion is kinda not easy to understand to every coder, so i wanted to create a class in our enterprise framework that would do the job.</p>
  
  <p>What do you think about it? Do you see something bad about it? Is there something similar like in Apache Commons? How can i make it better?</p>
  
  <p>Supplier.java</p>
  
  <pre><code>public interface Supplier&lt;T&gt; {
      public T get();
  }
  </code></pre>
  
  <p>LazyThreadSafeInstantiator.java</p>
  
  <pre><code>public class LazyThreadSafeInstantiator&lt;T&gt; implements Supplier&lt;T&gt; {
      private final Supplier&lt;T&gt; instanceSupplier;
  
      private volatile T obj;
  
      public LazyThreadSafeInstantiator(Supplier&lt;T&gt; instanceSupplier) {
          this.instanceSupplier = instanceSupplier;
      }
  
      @Override
      // http://en.wikipedia.org/wiki/Double-checked_locking
      public T get() {
          T result = obj;  // Wikipedia: Note the usage of the local variable result which seems unnecessary. For some versions of the Java VM, it will make the code 25% faster and for others, it won't hurt.
          if (result == null) {
              synchronized(this) {
                  result = obj;
                  if (result == null) {
                      result = instanceSupplier.get();
                      obj = result;
                  }
              }
          }
          return result;
      }
  }
  </code></pre>
  
  <p>Example usage:</p>
  
  <pre><code>public class Singleton1 {
      private static final Supplier&lt;Singleton1&gt; instanceHolder =
          new LazyThreadSafeInstantiator&lt;Singleton1&gt;(new Supplier&lt;Singleton1&gt;() {
              @Override
              public Singleton1 get() {
                  return new Singleton1();
              }
          });
  
      public Singleton1 instance() {
          return instanceHolder.get();
      }
  
      private Singleton1() {
          System.out.println("Singleton1 instantiated");
      }
  }
  </code></pre>
  
  <p>Thanks</p>