The removeEldestEntry Hook Method
What you'll learn: How LinkedHashMap lets you automatically evict the oldest entry when the map grows too large.
When building an LRU cache with LinkedHashMap, you need a way to limit its size. Otherwise, your cache could grow indefinitely. Java provides an elegant solution: the removeEldestEntry method.
How It Works
Every time you insert a new entry (via put), LinkedHashMap automatically calls the protected method removeEldestEntry(Map.Entry<K,V> eldest). This method receives the oldest entry as an argument and returns a boolean:
true: Remove the oldest entryfalse: Keep it (default behavior)
By default, removeEldestEntry always returns false, so nothing is ever removed automatically. But you can override it to enforce a maximum size.
Overriding for Size Limits
To create a self-limiting cache, extend LinkedHashMap and override removeEldestEntry:
LinkedHashMap<String, Integer> cache = new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
return size() > 100; // Remove oldest when size exceeds 100
}
};
Now when you add the 101st entry, the oldest entry automatically disappears. Combined with access-order mode (true in the constructor), this creates a perfect LRU cache that maintains only the 100 most-recently-used items.
The Hook Pattern
This is an example of the Template Method pattern: LinkedHashMap defines the insertion algorithm, but lets you customize one specific decision point (whether to remove old entries) by overriding a hook method.
Key Takeaway: Override removeEldestEntry to return true when your map exceeds a desired size, enabling automatic eviction of the oldest entry after each insertion—perfect for implementing size-limited LRU caches.