title: Java: what is the correct way to guarantee a non-final reference field will never be read as null?
body: <p>I'm trying to solve a simple problem and am falling into a Java Memory Model rabbit hole.</p>
  
  <p>What is the simplest and/or most efficient (judgement call here), but race-free (precisely defined according to the JMM) way to write a Java class containing a <strong>non-final</strong> reference field which is initialized to a non-null value in the constructor and subsequently never changed, such that no subsequent access of that field by any other thread can see a non-null value?</p>
  
  <p>Broken starting example:</p>
  
  <pre><code>public class Holder {
  
    private Object value;
  
    public Holder(Object value) {
      if (value == null)
          throw NullPointerException();
      this.value = value;
    }
  
    public Object getValue() {    // this could return null!
      return this.value;
    }
  }
  </code></pre>
  
  <p>And according to <a href="http://cs.oswego.edu/pipermail/concurrency-interest/2013-November/011954.html" rel="nofollow noreferrer">this post</a>, marking the field <code>volatile</code> doesn't even work!</p>
  
  <pre><code>public class Holder {
  
    private volatile Object value;
  
    public Holder(Object value) {
      if (value == null)
          throw NullPointerException();
      this.value = value;
    }
  
    public Object getValue() {    // this STILL could return null!!
      return this.value;
    }
  }
  </code></pre>
  
  <p>Is this the best we can do??</p>
  
  <pre><code>public class Holder {
  
    private Object value;
  
    public Holder(Object value) {
      if (value == null)
          throw NullPointerException();
      synchronized (this) {
          this.value = value;
      }
    }
  
    public synchronized Object getValue() {
      return this.value;
    }
  }
  </code></pre>
  
  <p>OK what about this?</p>
  
  <pre><code>public class Holder {
  
    private Object value;
  
    public Holder(Object value) {
      if (value == null)
          throw NullPointerException();
      this.value = value;
      synchronized (this) { }
    }
  
    public synchronized Object getValue() {
      return this.value;
    }
  }
  </code></pre>
  
  <p>Side note: a <a href="https://stackoverflow.com/questions/22565155/cheapest-way-of-establishing-happens-before-with-non-final-field">related question</a> asks how to do this without using any <code>volatile</code> or synchronization, which is of course impossible.</p>