title: Does Java synchronized keyword flush the cache?
body: <p>Java 5 and above only.  Assume a multiprocessor shared-memory computer (you're probably using one right now).</p>
  
  <p>Here is a code for lazy initialization of a singleton:</p>
  
  <pre><code>public final class MySingleton {
    private static MySingleton instance = null;
    private MySingleton() { } 
    public static MySingleton getInstance() {
      if (instance == null) {
        synchronized (MySingleton.class) {
          if (instance == null) {
            instance = new MySingleton();
          }
        }
      }
      return instance;
    }
  }
  </code></pre>
  
  <p>Does <code>instance</code> have to be declared <code>volatile</code> in order to prevent the optimizer from rewriting getInstance() as follows (which would be correct in a sequential program):</p>
  
  <pre><code>public static MySingleton getInstance() {
    if (instance == null) {
      synchronized (MySingleton.class) {
        // instance must be null or we wouldn't be here  (WRONG!)
        instance = new MySingleton();
      }
    }
  }
  </code></pre>
  
  <p>Assuming the optimizer does not rewrite the code, if <code>instance</code> is not declared <code>volatile</code> is it still guaranteed to be flushed to memory when the <code>synchronized</code> block is exited, and read from memory when the <code>synchronized</code> block is entered?</p>
  
  <p>EDIT:  I forgot to make getInstance() static. I don't think that changes the validity of the answers; you all knew what I meant.</p>