title: Demonstrating problems with improperly published objects
body: <p>JCIP warns us against improperly published objects (see <a href="https://stackoverflow.com/a/6812936/55094">here</a>). If an object is mutable, the JVM might decide to publish the object before its initialization was finished.</p>
  
  <p>So the code</p>
  
  <pre><code>class Holder {public int h = 0;public Holder(int _h) {h = _h;}}
  a = new Holder(10);
  </code></pre>
  
  <p>could become effectively</p>
  
  <pre><code>a = new Holder();
  // inlined constructor
  a.h = 10;
  </code></pre>
  
  <p>then when different thread access <code>a.h</code>, assuming it can never be 0, it could fail</p>
  
  <pre><code>// Thread #1 executing
  a = new Holder();
  // Thread #2 preempts
  if (a != null) System.out.println("result: "+(100/a.h)); // oops...
  </code></pre>
  
  <p>I was trying to demonstrate this problem. But no code I wrote demonstrated it. What I did was a holder</p>
  
  <pre><code>static class Holder {
      int h = 0;
      int dummy = 0;
      public Holder(int h) {
          // if construction takes time, maybe I have better chance creating the bug...
          for (long i=0;i&lt;1000*1000;i++) {
              dummy += i*(-1+(i%2*2));
          }
          this.h = h;
      }
      public int verifyNonZero() {
          return 1/h;
      }
  }
  </code></pre>
  
  <p>Then I ran 1000 threads publishing <code>new Holder()</code> to a static <code>holder</code> variable, and other 1000 threads running <code>holder.verifyNonZero()</code>. See <a href="https://gist.github.com/1502541" rel="nofollow noreferrer">full gist</a>.</p>
  
  <p>It didn't really help with Java 1.6, even with <code>-server</code>.</p>