title: Are static variables shared between threads?
body: <p>My teacher in an upper level Java class on threading said something that I wasn't sure of.</p>
  
  <p>He stated that the following code would not necessarily update the <code>ready</code> variable.  According to him, the two threads don't necessarily share the static variable, specifically in the case when each thread (main thread versus <code>ReaderThread</code>) is running on its own processor and therefore doesn't share the same registers/cache/etc and one CPU won't update the other.</p>
  
  <p>Essentially, he said it is possible that <code>ready</code> is updated in the main thread, but NOT in the <code>ReaderThread</code>, so that <code>ReaderThread</code> will loop infinitely.</p>
  
  <p>He also claimed it was possible for the program to print <code>0</code> or <code>42</code>.  I understand how <code>42</code> could be printed, but not <code>0</code>.  He mentioned this would be the case when the <code>number</code> variable is set to the default value.</p>
  
  <p>I thought perhaps it is not guaranteed that the static variable is updated between the threads, but this strikes me as very odd for Java.  Does making <code>ready</code> volatile correct this problem?</p>
  
  <p>He showed this code:  </p>
  
  <pre><code>public class NoVisibility {  
      private static boolean ready;  
      private static int number;  
      private static class ReaderThread extends Thread {   
          public void run() {  
              while (!ready)   Thread.yield();  
              System.out.println(number);  
          }  
      }  
      public static void main(String[] args) {  
          new ReaderThread().start();  
          number = 42;  
          ready = true;  
      }  
  }
  </code></pre>