title: Why doesn't volatile in java 5+ ensure visibility from another thread?
body: <p>According to:</p>
  
  <p><a href="http://www.ibm.com/developerworks/library/j-jtp03304/">http://www.ibm.com/developerworks/library/j-jtp03304/</a></p>
  
  <blockquote>
    <p>Under the new memory model, when thread A writes to a volatile variable V, and thread B reads from V, any variable values that were visible to A at the time that V was written are guaranteed now to be visible to B</p>
  </blockquote>
  
  <p>And many places on the internet state that the following code should never print "error":</p>
  
  <pre><code>public class Test {
      volatile static private int a;
      static private int b;
  
      public static void main(String [] args) throws Exception {
          for (int i = 0; i &lt; 100; i++) {
              new Thread() {
  
                  @Override
                  public void run() {
                      int tt = b; // makes the jvm cache the value of b
  
                      while (a==0) {
  
                      }
  
                      if (b == 0) {
                          System.out.println("error");
                      }
                  }
  
              }.start();
          }
  
          b = 1;
          a = 1;
      }
  }
  </code></pre>
  
  <p><code>b</code> <strong>should</strong> be 1 for all the threads when <code>a</code> is 1.</p>
  
  <p>However <strong>I sometimes get "error" printed</strong>. How is this possible?</p>