title: How to do a lazy create and set with AtomicReference in a safe and efficient manner?
body: <p>I'm looking to lazily create something and cache the results as an optimization.  Is the code below safe and efficient, or is there a better way to do this?  Is the compare and set loop needed here?</p>
  
  <pre><code>...
  AtomicReference&lt;V&gt; fCachedValue = new AtomicReference&lt;&gt;();
  
  public V getLazy() {
      V result = fCachedValue.get();
      if (result == null) {
          result = costlyIdempotentOperation();
          fCachedValue.set(result);
      }
      return result; 
  } 
  </code></pre>
  
  <p>edit:  The value being set in my example here from costlyIdempotentOperation() would always be the same no matter what thread called it.</p>