title: Thread-safe cache of one object in java
body: <p>let's say we have a CountryList object in our application that should return the list of countries. The loading of countries is a heavy operation, so the list should be cached. </p>
  
  <p>Additional requirements:</p>
  
  <ul>
  <li>CountryList should be thread-safe</li>
  <li>CountryList should load lazy (only on demand)</li>
  <li>CountryList should support the invalidation of the cache</li>
  <li>CountryList should be optimized considering that the cache will be invalidated very rarely</li>
  </ul>
  
  <p>I came up with the following solution:</p>
  
  <pre><code>public class CountryList {
      private static final Object ONE = new Integer(1);
  
      // MapMaker is from Google Collections Library    
      private Map&lt;Object, List&lt;String&gt;&gt; cache = new MapMaker()
          .initialCapacity(1)
          .makeComputingMap(
              new Function&lt;Object, List&lt;String&gt;&gt;() {
                  @Override
                  public List&lt;String&gt; apply(Object from) {
                      return loadCountryList();
                  }
              });
  
      private List&lt;String&gt; loadCountryList() {
          // HEAVY OPERATION TO LOAD DATA
      }
  
      public List&lt;String&gt; list() {
          return cache.get(ONE);
      }
  
      public void invalidateCache() {
          cache.remove(ONE);
      }
  }
  </code></pre>
  
  <p>What do you think about it? Do you see something bad about it? Is there other way to do it? How can i make it better? Should i look for totally another solution in this cases?</p>
  
  <p>Thanks.</p>