Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
One lock
What a race does to a list, and the first honest fix
The point: get and put each change two structures and six pointers. Make each of them one step with one lock, and do the sum before you look for something better.
Bug
Half an unlink
Thread A reads key 1 and has done the first of two writes. Thread B stores key 4, evicts the last node, which happens to be node 1, and links its own. Then A goes on.
class N: def __init__(self, name): self.name, self.prev, self.next = name, None, Nonehead, tail = N("head"), N("tail")nodes = [N(str(k)) for k in (3, 2, 1)]chain = [head, *nodes, tail]for a, b in zip(chain, chain[1:]): a.next, b.prev = b, adef unlink(n): # a generator: at each yield the other thread may run n.prev.next = n.next yield n.next.prev = n.prevdef push(n): n.prev, n.next = head, head.next head.next.prev = n head.next = none = nodes[2]a = unlink(one) # thread A: get(1), first halfnext(a)for _ in unlink(tail.prev): # thread B: put(4) evicts the last one, which is node 1 passpush(N("4"))for _ in a: # thread A goes on passpush(one) # and links an evicted node to the frontdef walk(start, step): out, n = [], getattr(start, step) while n not in (head, tail): out.append(n.name) n = getattr(n, step) return outprint("forward ", walk(head, "next"))print("backward", walk(tail, "prev"))print("in the map: 2, 3, 4")yield is a moment where the other one may run. The result holds four nodes, the map three, and node 1 will be evicted a second time later.What such a list does afterwards
| Damage | When you notice |
|---|---|
| A node points at itself or forms a ring | A walk never ends. One processor core is busy for ever |
| The list knows a node the map does not | At its eviction: key not found, or the wrong entry is removed |
| The map knows a node that is in no list | At its next touch: a null pointer |
| A lost update | Never. The hit rate is a little worse |
Fix
One lock, whole methods
final class LockedCache<K, V> { private final Object lock = new Object(); // private: nobody outside can hold it private final LruCache<K, V> inner; // guarded by lock LockedCache(int capacity) { inner = new LruCache<>(capacity); } V get(K key) { synchronized (lock) { return inner.get(key); } } Map.Entry<K, V> put(K key, V value) { synchronized (lock) { return inner.put(key, value); } } V computeIfAbsent(K key, Function<K, V> load) { // get, then put, without a gap synchronized (lock) { V value = inner.get(key); if (value == null) { value = load.apply(key); // only if load is quick. See Loading once inner.put(key, value); } return value; } }}| Rule | Why | Without it |
|---|---|---|
| The whole method under the lock | Lookup and touch are one step | The node is evicted between them |
| One lock for map and list | The invariant is about both | Two locks, and a state in between |
| A private lock object | Only this class decides how long it is held | Somebody locks the cache around a network call |
| No callbacks and no loads inside | Unknown code may be slow or may call us back | Everybody waits, or a deadlock |
Offer computeIfAbsent | get then put from outside is two steps | Two threads load the same key |
Sum
How busy is the lock?
Share of the time the lock is held
Say the assumption aloud and say what would change your mind: a profile that shows threads waiting. In Python the interpreter adds its own limit, so more locks help less there than in Java or C++.
synchronized or ReentrantLock?
Breakssynchronized on the map
- How
- Lock the map object that others can reach.
- Limit
- Their code can hold your lock.
- Choose when
- Never.
Workssynchronized on a private object
- How
- Released on every way out, also on errors.
- Limit
- No timeout, no try.
- Choose when
- The default.
StrongReentrantLock, when you need tryLock
- How
- lock, try, finally unlock.
tryLocklets a reader skip its touch when the lock is busy. - Limit
- Forget the finally, and the cache stands still for ever.
- Choose when
- Approximate recency: see Read lock and Buffered reads.