Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Concurrent map
Lock-free lookups, and the ghosts they bring
The point: a concurrent map makes the lookup safe, not the pair of lookup and touch. Whatever was found outside the lock must be checked again inside.
Bug
The ghost at the front
The idea is good: look up without a lock, then take a small lock only to move the node. Between the two, somebody may evict the node. Then you link a node to the front that the map has forgotten.
from collections import OrderedDictclass HalfLocked: """A safe map, and a separate lock for the order only.""" def __init__(self, capacity): self.capacity, self.map, self.order = capacity, {}, OrderedDict() def get_steps(self, key): node = self.map.get(key) # no lock: the map is safe by itself yield self.order[key] = node # later, under the lock of the list self.order.move_to_end(key) def put(self, key, value): if len(self.map) == self.capacity: oldest, _ = self.order.popitem(last=False) del self.map[oldest] self.map[key] = self.order[key] = valuecache = HalfLocked(2)cache.put("a", 1)cache.put("b", 2)reader = cache.get_steps("a")next(reader) # the reader has found acache.put("c", 3) # somebody evicts afor _ in reader: # the reader moves it to the front passprint("map ", sorted(cache.map)) # ['b', 'c']print("order", list(cache.order)) # a is back, and no map entry leads to itFix
Check again under the lock
final class ConcurrentLruCache<K, V> { private final int capacity; private final ConcurrentHashMap<K, Node<K, V>> nodes = new ConcurrentHashMap<>(); private final RecencyList<K, V> order = new RecencyList<>(); // guarded by lock private final Object lock = new Object(); ConcurrentLruCache(int capacity) { this.capacity = capacity; } V get(K key) { Node<K, V> node = nodes.get(key); // no lock if (node == null) return null; synchronized (lock) { if (nodes.get(key) == node) order.touch(node); // same node, still in the map } return node.value; // value must be volatile } void put(K key, V value) { synchronized (lock) { // all writers go through here Node<K, V> node = nodes.get(key); if (node != null) { node.value = value; order.touch(node); return; } if (nodes.size() >= capacity) { // not >, or the cache holds one too many Node<K, V> last = order.last(); order.unlink(last); nodes.remove(last.key); } node = new Node<>(key, value); order.pushFront(node); nodes.put(key, node); // visible only when it is linked } }}head and tail are final, they never change, so they need no volatile. Only value does.Five details, five bugs
| Detail | Without it |
|---|---|
nodes.get(key) == node inside the lock | Ghost entries, or a null pointer in touch |
value is volatile | A reader may not see an update for a long time |
>= and not > | Capacity plus one |
| Link before you publish | A reader finds a node without neighbours and touches it |
| All changes to the map under the lock | Two puts of a new key make two nodes, one is in the list only |
What did it win?
Misses take no lock. Hits still take it, for a shorter time. So the gain is real for a cache with many misses, and those are the caches that help least. The next two pages attack the hit.
About ConcurrentHashMap itself
- 1
Reads
Retrievals generally do not block. That is the part we use.
- 2
Writes
It locks a small part, in current versions one bin of the table. The segments that people still describe are from Java 7 and before.
- 3
size
Its documentation says such results are for monitoring and estimation, not for program control, while others write. Here every writer holds our lock, so the number is exact.
- 4
Two calls
Each call is atomic, a pair is not. Use compute, computeIfAbsent or a lock for a pair.
A hit takes the lock. How do you shorten it?
BreaksSkip the check of the node
- How
- Touch what you found.
- Limit
- Ghosts.
- Choose when
- Never.
WorksCheck again, touch, leave
- How
- As above.
- Limit
- Every hit still queues.
- Choose when
- Moderate load, many misses.
StrongDo not touch on each hit
- How
- Notes in a buffer, or once a second.
- Limit
- Approximate order.
- Choose when
- Many hits.