LRU Map

2 AM November 19, 2004

I went looking for a light-weight cache today and found the LRUMap class buried in Commons-collections. LRUMap works just like a normal map except that it can only contain a certain number of items. When your code tries to insert more than that number of items, the LRUMap evicts the least recently accessed item.


Map cache = new LRUMap(3);

cache.put(“A”, “Aardvark”);

cache.put(“B”, “Bobcat”);

cache.put(“C”, “Kitten”);

// Prints “Aardvark” and makes “Bobcat” the

// Least Recently Used key

System.out.println(cache.get(“A”));

cache.put(“D”, “Dinosaur”);

// Prints Aardvark, null, Kitten, Dinosaur

System.out.println(cache.get(“A”));

System.out.println(cache.get(“B”));

System.out.println(cache.get(“C”));

System.out.println(cache.get(“D”));

By alang | # | Comments (3)
(Posted to javablogs and Java)

Comments

At 14:55, 19 Nov 2004 Cameron wrote:

Sure you don't want to cluster? ;-)

(#)
At 04:05, 20 Nov 2004 Charles Miller wrote:

I discovered recently (through another blog post) that you can do the same thing with the JDK1.4 LinkedHashMap, by overriding removeEldestEntry():

http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedHashMap.html#removeEldestEntry(java.util.Map.Entry)

(#)
At 08:39, 21 Nov 2004 Alan Green wrote:

Neat. Maybe it was Jonathan Schwartz's blog?

http://blogs.sun.com/roller/page/swinger/20041012#collections_trick_i_lru_cache

To make LinkedHashmap work like LRUMap, you need to use the constructor with the boolean parameter, and create a subclass that overrides removeEldestEntry.

(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green