Video in progress
How do you write a simple LRU cache using LinkedHashMap?
You create the LinkedHashMap with accessOrder = true and override removeEldestEntry: when the size goes over the limit, the least recently used entry is removed automatically. In a multithreaded environment you need to wrap it or use a ready-made cache library.
📖 Answer
public class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int maxSize;
public LruCache(int maxSize) {
super(16, 0.75f, true); // true: access order
this.maxSize = maxSize;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
}
var cache = new LruCache<String, String>(2);
cache.put("a", "1");
cache.put("b", "2");
cache.get("a"); // "a" is now the most recent
cache.put("c", "3"); // "b" was evicted
With accessOrder = true, get also moves the entry to the end of the list. So even a plain get changes the structure, which means even "read-only" use is not safe from multiple threads. If you call get during iteration, you can get a CME too.
This solution is fine for tests, small utilities or a single thread. On prod, if you need multiple threads, a TTL or statistics, I take Caffeine: it gives a better hit rate and runs much faster than a LinkedHashMap wrapped in a lock.
Sign up to mark studied questions and save your progress.