Caching in Java with LRUMap

So you want to cache recently used values? Well, there’s LRUMap for that!

LRU stands for Least Recently Used. LRUMap uses the LRU algorithm to delete the least recently used value in the map (presumably full) to make space for the newest entry.

You can use LRUMap through the Apache Commons Collections library. You can download the jar file here.

So, how do you instantiate this thing?

You can use the default constructor, or you can define its maximum size in the constructor. Its default maximum size is 100.

Map<Object, Object> map = new LRUMap();
Map<Object, Object> map = new LRUMap(100);

Beware: The LRUMap isn’t synchronized and thread safe. If you want to make it synchronized you can use java.util.Collections.synchronizedMap(Map) to wrap around the LRUMap and instantiate it like so…

Map<Object, Object> map = (Map<Object, Object>) Collections.synchronizedMap(new LRUMap());
Map<Object, Object> map = (Map<Object, Object>) Collections.synchronizedMap(new LRUMap(100));


import java.util.Collections;
import java.util.Map;


public class LRUSample {

	private static final int MAX_CAPACITY = 5;

	public static void main(String[] args) {
		Map<Integer, String> lruMap = (Map<Integer, String>) Collections.synchronizedMap(new LRUMap(MAX_CAPACITY));

		for(int i = 0; i < 30; i++) {
			String string = "Entry " + (i + 1);
			lruMap.put(i, string);



LinkedHashMap as an Alternative

Okay, well if you don’t feel like using LRUMap, you can also use a LinkedHashMap. You can read about it (there’s a sample too) from this blog post.

Leave a Reply

Your email address will not be published. Required fields are marked *