title: How do I efficiently cache objects in Java using available RAM?
body: <p>I need to cache objects in Java using a proportion of whatever RAM is available.  I'm aware that others have asked this question, but none of the responses meet my requirements.</p>
  
  <p>My requirements are:</p>
  
  <ul>
  <li>Simple and lightweight</li>
  <li>Not dramatically slower than a plain HashMap</li>
  <li>Use LRU, or some deletion policy that approximates LRU</li>
  </ul>
  
  <p>I tried LinkedHashMap, however it requires you to specify a maximum number of elements, and I don't know how many elements it will take to fill up available RAM (their sizes will vary significantly).</p>
  
  <p>My current approach is to use Google Collection's MapMaker as follows:</p>
  
  <pre><code>Map&lt;String, Object&gt; cache = new MapMaker().softKeys().makeMap();
  </code></pre>
  
  <p>This seemed attractive as it should automatically delete elements when it needs more RAM, however there is a serious problem: its behavior is to fill up all available RAM, at which point the GC begins to thrash and the whole app's performance deteriorates dramatically.</p>
  
  <p>I've heard of stuff like EHCache, but it seems quite heavy-weight for what I need, and I'm not sure if it is fast enough for my application (remembering that the solution can't be dramatically slower than a HashMap).</p>