title: How to cache information in a DAO in a threadsafe manner
body: <p>I often need to implement DAO's for some reference data that doesn't change very often. I sometimes cache this in collection field on the DAO - so that it is only loaded once and explicitly updated when required. </p>
  
  <p>However this brings in many concurrency issues - what if another thread attempts to access the data while it is loading or being updated. </p>
  
  <p>Obviously this can be handled by making both the getters and setters of the data synchronised - but for a large web application this is quite an overhead.</p>
  
  <p>I've included a trivial flawed example of what I need as a strawman. Please suggest alternative ways to implement this. </p>
  
  <pre><code>public class LocationDAOImpl implements LocationDAO {
  
  private List&lt;Location&gt; locations = null;
  
  public List&lt;Location&gt; getAllLocations() {
      if(locations == null) {
          loadAllLocations();
      }
      return locations;
  }
  </code></pre>
  
  <p>For further information I'm using Hibernate and Spring but this requirement would apply across many technologies. </p>
  
  <p>Some further thoughts:</p>
  
  <p>Should this not be handled in code at all - instead let ehcache or similar handle it?
  Is there a common pattern for this that I'm missing?
  There are obviously many ways this can be achieved but I've never found a pattern that is simple and maintainable.</p>
  
  <p>Thanks in advance!</p>