title: Double Checked Locking in Singleton
body: <p>here is my custom class for singleton pattern. in this code, I use double-checked locking as below. As I read many posts on some source, they say that double check is useful because it prevents two concurrent threads run at same times make two different objects.</p>
  
  <pre><code>public class DoubleCheckLocking {
  
      public static class SearchBox {
          private static volatile SearchBox searchBox;
  
          // private constructor
          private SearchBox() {}
  
          // static method to get instance
          public static SearchBox getInstance() {
              if (searchBox == null) { // first time lock
                  synchronized (SearchBox.class) {
                      if (searchBox == null) {  // second time lock
                          searchBox = new SearchBox();
                      }
                  }
              }
              return searchBox;
          }
  }
  </code></pre>
  
  <p>I still don't understand above code so much. What is the problem, if two threads together run same line of code when instance is null ?</p>
  
  <pre><code>if (searchBox == null) {
                  synchronized (SearchBox.class) {
                      if (searchBox == null) {
                          searchBox = new SearchBox();
                      }
                  }
              }
  </code></pre>
  
  <p>When that appear. both two threads will see object is null. then both synchronize. and then, <strong>they check again, and still see it null</strong>. and create two different objects. OOOPS.</p>
  
  <p>Please explain for me. What have I understand wrong ? </p>
  
  <p>Thanks :)</p>