Build a small LRU cache with LinkedHashMap
Java
import java.util.LinkedHashMap;
import java.util.Map;
/** A fixed-capacity, thread-confined LRU cache built on LinkedHashMap. */
public final class LruCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int capacity;
public LruCache(int capacity) {
super(Math.max(16, capacity * 2), 0.75f, true); // true = access order
if (capacity <= 0) {
throw new IllegalArgumentException("capacity must be positive");
}
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
public static void main(String[] args) {
var cache = new LruCache<String, Integer>(2);
cache.put("a", 1);
cache.put("b", 2);
cache.get("a"); // "a" becomes the most recently used
cache.put("c", 3); // evicts "b"
System.out.println(cache.keySet()); // [a, c]
}
}