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


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

// Prints Aardvark, null, Kitten, Dinosaur





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


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():

At 08:39, 21 Nov 2004 Alan Green wrote:

Neat. Maybe it was Jonathan Schwartz's blog?

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