AlgoViz

Design an LRU cache

medium 85 min

Design 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.

Python
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")
The unlucky order without any thread: each 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.
Edit and run it in your browser

What such a list does afterwards

DamageWhen you notice
A node points at itself or forms a ringA walk never ends. One processor core is busy for ever
The list knows a node the map does notAt its eviction: key not found, or the wrong entry is removed
The map knows a node that is in no listAt its next touch: a null pointer
A lost updateNever. The hit rate is a little worse

Fix

One lock, whole methods

Java
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;        }    }}
The lock is a layer, and the cache below stays the plain one. The inner cache never escapes, so no call can go around the lock.
RuleWhyWithout it
The whole method under the lockLookup and touch are one stepThe node is evicted between them
One lock for map and listThe invariant is about bothTwo locks, and a state in between
A private lock objectOnly this class decides how long it is heldSomebody locks the cache around a network call
No callbacks and no loads insideUnknown code may be slow or may call us backEverybody waits, or a deadlock
Offer computeIfAbsentget then put from outside is two stepsTwo threads load the same key

Sum

How busy is the lock?

Share of the time the lock is held

ρ=200,000 calls/s×1 μs=0.2\rho = 200{,}000\ \text{calls/s} \times 1\ \mu s = 0.2
Assumed: 1 microsecond under the lock for each call. At 20 percent waiting is rare. At a million calls a second the sum is 1.0, and the lock is the limit.

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. tryLock lets 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.