title: HashMap with weak values
body: <p>I'm implementing a cache for Objects stored persistently. The idea is:</p>
  
  <ul>
  <li>Method <code>getObjectFromPersistence(long id);  ///Takes about 3 seconds</code></li>
  <li>Method <code>getObjectFromCache(long id)  //Instantly</code></li>
  </ul>
  
  <p>And have a method: <code>getObject(long id)</code> with the following pseudocode:</p>
  
  <pre><code>synchronized(this){
      CustomObject result= getObjectFromCache(id)
      if (result==null){
         result=getObjectFromPersistence(id);
         addToCache(result);
      }
      return result;
  }
  </code></pre>
  
  <p>But I need to allow the CustomObject to be collected by the garbage collector. Until now I was using an <code>HashMap&lt;Long,WeakReference&lt;CustomObject&gt;</code> for the implementation. The problem is that over the time the HashMap becomes filled of empty <code>WeakReferences</code>. </p>
  
  <p>I've checked <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/WeakHashMap.html" rel="noreferrer">WeakHashMap</a> but there the keys are weak  (and the values are still strong references) so having the longs with WeakReferences have no sense.</p>
  
  <p>Whats the best solution for solving this problem? Is there some "inverse WeakHashMap" or something similar?</p>
  
  <p>Thanks</p>