The JDK is full of gems. My latest discovery began with a need for a simple in memory “least recently used” (LRU) cache. I wanted a hash map with limited size. When the cache is full, it should remove the least recently used item, keeping the more popular items in memory. I figured there was probably an existing implementation in java.util, but nothing fit, until I ran across some posts that mentioned “LinkedHashMap” as a possible solution…Bingo. The java doc even mentions this type of application and provides an abstraction ready for implementation when you extend LinkedHashMap,
removeEldestEntry()
Today I found a good example with documentation, for anyone who is curious, or would like an off the shelf ready to use example of LRU cache for java, see
http://www.source-code.biz/snippets/java/6.htm
You need not create your own class. You can also specifiy the LRU-settings when creating instances of a LinkedHashMap.
Please see the example for LRU-caching on http://www.java-blog.com/creating-simple-cache-java-linkedhashmap-anonymous-class
Or just use the LRUMap class from Jakarta Commons Collections.
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html
Hi. When using LinkedHashMap with removeEldestEntry: isn’t it actually “Least Recently _Added_” policy?
I believe, that LRU would require moving an entry to the front, in “get(….)” method.
And, AFAIK, to move an entry to the front, it is required to remove the item and then re-add it.
Ok, sorry, i just java.util.LinkedHashMap.LinkedHashMap(int, float, boolean) , third param