title: Singleton with static inner class and double-checked locking
body: <p>I am reading about Singleton design pattern and evaluating different implementations. I have doubt with the below implementations:</p>
  
  <p><strong>A. Singleton Implementation with static inner class</strong> </p>
  
  <pre><code>public class SingletonWithStaticClass {
  
  private SingletonWithStaticClass(){}
  
  private static class SingletonInnerClass{
      public static SingletonWithStaticClass INSTANCE = new SingletonWithStaticClass();
  
  }
  
  public static SingletonWithStaticClass getInstance(){
      return SingletonInnerClass.INSTANCE;
  }
  </code></pre>
  
  <p>} </p>
  
  <p><strong>B. Singleton double checked locking</strong> </p>
  
  <pre><code>public class SingletonWithDoubleCheck {
  private static SingletonWithDoubleCheck INSTANCE = null;
  
  private SingletonWithDoubleCheck(){
      if(INSTANCE != null){
          throw new RuntimeException("Accessing private constructor is prohibited. Use getInstance method instead");
      }
  }
  
  public static SingletonWithDoubleCheck getInstance(){
      if(INSTANCE == null){
          synchronized (SingletonWithDoubleCheck.class) {
              if(INSTANCE == null){
                  INSTANCE = new SingletonWithDoubleCheck();
              }
          }
      }
      return INSTANCE;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>Which one is better?</p>
  
  <p>I feel we can access the private constructor with Reflection in first implementation where as second implementation is safe (From Reflection attack). </p>
  
  <p>However, I am not going to use any of these in my production code, I will use <strong><em>enum</em></strong> instead. But out of these two, isn't the first implementation is broken when considered Reflection attack? </p>
  
  <p>Please correct me if my understanding is wrong.</p>