Debugging a LinkedHashMap-Based Eviction Cache in Java
Data Structure DesignModel answerLast updated
Review a Java cache built on LinkedHashMap that evicts the wrong entries, find each defect, write minimal failing tests, and produce a corrected version.
Review a Faulty Cache Implementation
A teammate opened a pull request adding a fixed-capacity cache that is supposed to discard the least recently used entry when it runs out of room. It is built on java.util.LinkedHashMap. The code compiles in the author's editor, yet the cache throws away the wrong entries in very ordinary usage.
import java.util.LinkedHashMap;
import java.util.Map;
public class SimpleLRUCache {
private final int capacity;
private final Map cache;
public SimpleLRUCache(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Capacity must be positive");
}
this.capacity = capacity;
// Intent: LRU eviction, given an initial capacity and the default load factor
this.cache = new LinkedHashMap(capacity, 0.75f) {
@Override
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() >= capacity;
}
};
}
public V get(K key) {
return cache.get(key);
}
public void put(K key, V value) {
cache.put(key, value);
}
public int size() {
return cache.size();
}
}
(Assume the intended class is generic over key type K and value type V.)
What to deliver
- Defects. List every way this code departs from correct LRU behavior, and say why each happens.
- Minimal failing tests. For each defect, give a short sequence of
put/getcalls whose expected result is correct for a proper LRU cache but wrong for this code. Ideally, each test should still fail if only the other defects are fixed. - Fix. Provide a corrected Java implementation.
- Why tests matter. Explain briefly why the compiler cannot flag these problems and why scenario-based behavioral tests are needed to protect a cache's invariants.
Hints
Hint 1
Look at which LinkedHashMap constructor is called. What iteration order does the two-argument form give you, and does a read change that order?
Hint 2
Ask when removeEldestEntry is invoked relative to the insertion, and what size() reports at that moment. Then think about what happens when the capacity is 1.
Hint 3
Check the declarations as well: the class and the map use raw types, so the generic signatures do not line up. Then design tests by filling the cache, touching an old key, and inserting one more key.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Invariants a correct LRU cache must hold
- Recency order. Every
getorputof a key makes it the most recently used. The victim is the least recently accessed entry, not the oldest inserted one. - Capacity bound. The cache stores up to
capacityentries and evicts only when a new key would push the size pastcapacity.
LinkedHashMap can provide both, but only if configured correctly. The submitted code breaks each invariant, and the declarations have a type-safety problem too.
Defects
1. Insertion order instead of access order.
new LinkedHashMap(capacity, 0.75f) leaves accessOrder at false. The map keeps insertion order and get never moves an entry, so the eldest entry is simply the first one inserted. The behavior is FIFO, not LRU. Fix: use the three-argument constructor LinkedHashMap<>(capacity, 0.75f, true).
2. Off-by-one in the eviction predicate.
LinkedHashMap.put calls removeEldestEntry after the new mapping is added, so size() already includes it. With size() >= capacity, eviction fires the moment the map becomes full, so the cache never holds more than capacity - 1 entries. For capacity = 1, the entry just inserted is also the eldest and is removed immediately, so the cache is always empty. Fix: size() > capacity.
3. Raw types and missing generics.
The class has no type parameters, yet its methods use K and V, so it does not compile as written. Even if patched, raw Map and raw Map.Entry switch off generic checking, and the removeEldestEntry override only matches through erasure. Declare SimpleLRUCache<K, V>, Map<K, V>, and Map.Entry<K, V>.
Minimal failing tests
Test A: recency (defect 1).
cache = new SimpleLRUCache<>(2)
put(1, "A"); put(2, "B")
get(1) // key 1 becomes most recent
put(3, "C") // should evict key 2
assert get(1).equals("A") // fails: key 1 was evicted
assert get(2) == null
If only defect 2 were fixed, insertion order would still make key 1 the eldest, so the test still fails.
Test B: capacity bound (defect 2).
cache = new SimpleLRUCache<>(2)
put(1, "A"); put(2, "B")
assert cache.size() == 2 // fails: size is 1
assert get(1).equals("A") // fails: key 1 was evicted by the second put
Test C: capacity of one (defect 2).
cache = new SimpleLRUCache<>(1)
put(1, "A")
assert get(1).equals("A") // fails: returns null
Corrected implementation
import java.util.LinkedHashMap;
import java.util.Map;
public class SimpleLRUCache<K, V> {
private final int capacity;
private final Map<K, V> cache;
public SimpleLRUCache(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("Capacity must be positive");
}
this.capacity = capacity;
// accessOrder = true: get/put move the entry to the tail (most recent)
this.cache = new LinkedHashMap<K, V>(capacity, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// Runs after insertion, so size() already counts the new entry
return size() > SimpleLRUCache.this.capacity;
}
};
}
public V get(K key) { return cache.get(key); }
public void put(K key, V value) { cache.put(key, value); }
public int size() { return cache.size(); }
}
Why this is correct
- In access-order mode, both
getand an overwritingputrelink the node at the tail, so the head is always the least recently used entry. removeEldestEntryis consulted only when a new mapping is created. Overwriting an existing key never evicts, which is right because the size is unchanged.- After a fresh insert the size is at most
capacity + 1; the> capacitytest then removes exactly the head, restoring the bound.
Complexity. get and put are O(1) on average (hash lookup plus constant-time relinking). Space is O(capacity).
Edge cases worth testing
capacity = 1, including overwriting the single key.puton an existing key in a full cache: updates the value, refreshes recency, evicts nothing.geton a missing key: returnsnull, order unchanged.- Null values:
nullfromgetis ambiguous between "absent" and "stored null". Either forbid null values or offercontainsKey, which does not update recency. - A sharing pitfall: the anonymous subclass reads
capacitythroughSimpleLRUCache.this, avoiding confusion with any shadowing field.
Why the compiler cannot catch this
Every defect is a perfectly well-typed program. Both LinkedHashMap(int, float) and LinkedHashMap(int, float, boolean) are valid overloads, and only documentation says which ordering each yields. >= and > are both legal boolean expressions. Types describe shapes (what goes in and out), not temporal invariants such as "the evicted key is the least recently accessed" or "size never exceeds capacity." Those only show up when you run a sequence of operations and inspect observable state. Hence each invariant needs a scenario test like A to C, ideally backed by a property-based test that runs random operation sequences against a trivial reference model (for example a list of keys ordered by recency).
Common mistakes
- Fixing only the constructor flag and leaving the
>=bug, then concluding the cache "mostly works" because capacity-3 tests look plausible. - Writing tests that only check
size(), which would miss the FIFO-versus-LRU defect. - Calling
containsKeyor iterating over the map in tests and assuming it counts as an access.
Follow-ups
Thread safety. In access-order mode, get is a structural modification because it relinks the list. A read-write lock with get under the read lock would corrupt the map. Use one exclusive lock (for example Collections.synchronizedMap), accepting serialized reads. To cut contention:
- Lock striping: split keys across N independent LRU segments, each with its own lock. Cost: eviction is only approximately global LRU.
- Buffered recency (Caffeine style): keep data in a
ConcurrentHashMapfor lock-free reads, record accesses in lock-free buffers, and replay them onto the recency list in batches under atryLock. Recency becomes eventually consistent. In production, prefer a library like this over hand-rolling.
From scratch with O(1) operations. Use a hash map from key to node plus a doubly linked list with sentinel head and tail. get unlinks the node and appends it at the tail. put updates and moves an existing node, or appends a new one and, if size exceeds capacity, removes head.next and its map entry.