title: Testing initialization safety of final fields
body: <p>I am trying to simply test out the initialization safety of final fields as guaranteed by the JLS.  It is for a paper I'm writing. However, I am unable to get it to 'fail' based on my current code.  Can someone tell me what I'm doing wrong, or if this is just something I have to run over and over again and then see a failure with some unlucky timing?</p>
  
  <p>Here is my code:</p>
  
  <pre><code>public class TestClass {
  
      final int x;
      int y;
      static TestClass f;
  
      public TestClass() {
          x = 3;
          y = 4;
      }
  
      static void writer() {
          TestClass.f = new TestClass();
      }
  
      static void reader() {
          if (TestClass.f != null) {
              int i = TestClass.f.x; // guaranteed to see 3
              int j = TestClass.f.y; // could see 0
  
              System.out.println("i = " + i);
              System.out.println("j = " + j);
          }
      }
  }
  </code></pre>
  
  <p>and my threads are calling it like this:</p>
  
  <pre><code>public class TestClient {
  
      public static void main(String[] args) {
  
          for (int i = 0; i &lt; 10000; i++) {
              Thread writer = new Thread(new Runnable() {
                  @Override
                  public void run() {
                      TestClass.writer();
                  }
              });
  
              writer.start();
          }
  
          for (int i = 0; i &lt; 10000; i++) {
              Thread reader = new Thread(new Runnable() {
                  @Override
                  public void run() {
                      TestClass.reader();
                  }
              });
  
              reader.start();
          }
      }
  }
  </code></pre>
  
  <p>I have run this scenario many, many times.  My current loops are spawning 10,000 threads, but I've done with this 1000, 100000, and even a million.  Still no failure.  I always see 3 and 4 for both values.  How can I get this to fail?</p>