title: my ideal cache using guava
body: <p>Off and on for the past few weeks I've been trying to find my ideal cache implementation using guava's <a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/MapMaker.html" rel="nofollow noreferrer" title="MapMaker">MapMaker</a>. See my previous two questions <a href="https://stackoverflow.com/questions/6289234/guava-mapmaker-optionally-set-maximumsize0-for-factory-method">here</a> and <a href="https://stackoverflow.com/questions/6592183/what-are-the-practical-consequences-of-using-soft-references">here</a> to follow my thought process.</p>
  
  <p>Taking what I've learned, my next attempt is going to ditch soft values in favor of maximumSize and expireAfterAccess:</p>
  
  <pre><code>ConcurrentMap&lt;String, MyObject&gt; cache = new MapMaker()
          .maximumSize(MAXIMUM_SIZE)
          .expireAfterAccess(MINUTES_TO_EXPIRY, TimeUnit.MINUTES)
          .makeComputingMap(loadFunction);
  </code></pre>
  
  <p>where</p>
  
  <pre><code>Function&lt;String, MyObject&gt; loadFunction = new Function&lt;String, MyObject&gt;() {
     @Override
     public MyObject apply(String uidKey) {
        return getFromDataBase(uidKey);
     }
  };
  </code></pre>
  
  <p>However, the one remaining issue I'm still grappling with is that this implementation will evict objects even if they are strongly reachable, once their time is up. This could result in multiple objects with the same UID floating around in the environment, which I don't want (I believe what I'm trying to achieve is known as canonicalization).</p>
  
  <p>So as far as I can tell the only answer is to have an additional map which functions as an interner that I can check to see if a data object is still in memory:</p>
  
  <pre><code>ConcurrentMap&lt;String, MyObject&gt; interner = new MapMaker()
          .weakValues()
          .makeMap();
  </code></pre>
  
  <p>and the load function would be revised:</p>
  
  <pre><code>Function&lt;String, MyObject&gt; loadFunction = new Function&lt;String, MyObject&gt;() {
     @Override
     public MyObject apply(String uidKey) {
        MyObject dataObject = interner.get(uidKey);
        if (dataObject == null) {
           dataObject = getFromDataBase(uidKey);
           interner.put(uidKey, dataObject);
        }
        return dataObject;
     }
  };
  </code></pre>
  
  <p>However, using two maps instead of one for the cache seems inefficient. Is there a more sophisticated way to approach this? In general, am I going about this the right way, or should I rethink my caching strategy?</p>