title: Lazy loading reference implementation
body: <p>Being impressed by Guava's <a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html#makeComputingMap%28com.google.common.base.Function%29" rel="nofollow noreferrer">computing map feature</a>, I'm searching for a sort of "computing reference" - a lazy loading reference implementation that parallel's Guava's ease of use, by which I mean it handles all locking, loading, and exception handling under the hood, only exposing a <code>get()</code> method.</p>
  
  <p>After a brief search turned up nothing, I quickly rolled my own as a proof of concept:</p>
  
  <pre><code>public abstract class ComputingRef&lt;T&gt; implements Callable&lt;T&gt; {
  
     private volatile T referent = null;
     private Lock lock = new ReentrantLock();
  
     public T get() {
        T temp = referent;
        if (temp == null) {
           lock.lock();
           try {
              temp = referent;
              if (temp == null) {
                 try {
                    referent = temp = call();
                 }
                 catch (Exception e) {
                    if (e instanceof RuntimeException) {
                       throw (RuntimeException)e;
                    }
                    else {
                       throw new RuntimeException(e);
                    }
                 }
              }
           }
           finally {
              lock.unlock();
           }
        }
        return temp;
     }
  }
  </code></pre>
  
  <p>This <code>ComputingRef</code> could be anonymously extended to implement <code>call()</code>, which functions as the factory method:</p>
  
  <pre><code>ComputingRef&lt;MyObject&gt; lazySingletonRef = new ComputingRef&lt;MyObject&gt;() {
     @Override
     public MyObject call() {
        //fetch MyObject from database and return
     }
  };
  </code></pre>
  
  <p>I'm not satisfied that this implementation is optimal, but it demonstrates what I'm after.</p>
  
  <p>I later found <a href="http://www.java2s.com/Code/Java/Collections-Data-Structure/LazyLoadingReference.htm" rel="nofollow noreferrer">this example from the T2 Framework</a>, which appears to be more complex.</p>
  
  <p>Now my questions are:</p>
  
  <ul>
  <li>How can my above code be improved?</li>
  <li>How does it compare to the T2 example, and what advantages are offered by that example's greater complexity?</li>
  <li>Are there other implementations of a lazy loading reference that I've missed in my search?</li>
  </ul>
  
  <p><strong>EDIT:</strong> Updated my implementation to use a local variable as suggested by <a href="https://stackoverflow.com/questions/7524423/lazy-loading-reference-implementation/7524565#7524565">@irreputable's answer</a> - please upvote it if you find the above example useful.</p>