title: Java synchronized with double if condition
body: <p>New to Java from C++ and came across this synchronized block example (more context on this <a href="http://javarevisited.blogspot.sg/2011/04/synchronization-in-java-synchronized.html" rel="nofollow noreferrer">page</a>). My question is:<br>
  <strike>Shouldn't the "if" statement also be included in the "synchronized block"? Or else other threads could be executing the same piece of code, pass the "if" checkpoint and thought that the "_instance" is null and then after the current thread finishes executing the synchronized block (and creates a new instance), other thread(s) will create duplicated instances? Thanks!</strike></p>
  
  <p>Now I realized that the code was actually doing double-checking, I have a new question then, why is double-checking needed? Thanks!<br><br>
  The code block is copied below:</p>
  
  <pre><code>public class Singleton{ 
  private static volatile Singleton _instance; 
  public static Singleton getInstance(){
      if(_instance == null){ //Shouldn't this line be included in the synchronized block?
          synchronized(Singleton.class){
              if(_instance == null) _instance = new Singleton(); 
          }
      } 
      return _instance; 
  }
  </code></pre>