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”));
Comments
Sure you don't want to cluster? ;-)
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)
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.