title: What is wrong with my thread-safe class using AtomicBoolean
body: <p>I have a simple class that I want to test thread-safe using AtomicBoolean. it does not work if more than 2 threads tested. It throws NullPointerExcetion in doSome method in some threads: Can someone show me what I am wrong? Thanks.</p>
  
  <pre><code>package jcafe.common.utils;
  
  import java.util.concurrent.atomic.AtomicBoolean;
  
  public class ThreadSafeTest {
  
      private final AtomicBoolean initialized = new AtomicBoolean(false);
  
      private Object lazyObject = null;
  
      protected void initialize() {
          if (initialized.compareAndSet(false, true)) {
  
              // Some other expensive init here
              // Some other expensive init here
  
              this.lazyObject = new Object();
          }
      }
  
      public void doSome() {
          initialize();
  
          // NullPointerException here: this.lazyObject = null
          System.out.println(this.lazyObject.toString());
      }
  
      public static void main(String[] args) {
          final ThreadSafeTest test = new ThreadSafeTest ();
  
          for (int i = 0; i &lt; 100; i++) {
              Thread t = new Thread(new Runnable() {
  
                  @Override
                  public void run() {
                      test.doSome();
                  }
              });
              t.start();
          }
      }
  }
  </code></pre>