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)
© 2003-2006 Alan Green