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

Read lock

Why a read and write lock does not help

The point: a read and write lock pays when readers do not change anything. Here they do. Either every get takes the write lock, or the order becomes approximate. There is no third way.

Trap

Three attempts

  1. 1

    get under the read lock

    Several readers unlink nodes at the same time. The list breaks exactly as without a lock.

  2. 2

    Read lock, then upgrade

    Java's ReentrantReadWriteLock does not support upgrading. A thread that holds the read lock and asks for the write lock waits until all readers are gone, and it is one of them. It waits for ever.

  3. 3

    Read lock, release, write lock

    Correct if the lookup is repeated. But now each hit takes two locks, and the second is the exclusive one. It is slower than one plain lock.

Java
V get(K key) {    readLock.lock();    try {        if (!nodes.containsKey(key)) return null;    // a miss stays cheap    } finally {        readLock.unlock();                           // must be released first    }    writeLock.lock();    try {        Node<K, V> node = nodes.get(key);            // look again: it may be gone by now        if (node == null) return null;        order.touch(node);        return node.value;    } finally {        writeLock.unlock();    }}
The version that is often shown as the solution. It is correct, and its claim that many readers run together is not: every hit ends in the write lock. Only misses run side by side.

What do you gain?

A cache with a hit rate of 90 percent

VersionLocks for 100 getsExclusive
One plain lock100100
Read, then write100 read + 90 write90
Write lock always100100
The better the cache works, the less the read lock helps. 190 lock operations to save 10 exclusive ones.

Giving up a little exactness

Does the order have to be perfect? If a key is read a thousand times a second, moving it once a second is enough to keep it alive. Several real caches use this.

Java
V get(K key) {    Node<K, V> node = nodes.get(key);                // a ConcurrentHashMap    if (node == null) return null;    long now = clock.getAsLong();    if (now - node.touchedAt > 1_000 && lock.tryLock()) {   // at most once a second, and never wait        try {            if (nodes.get(key) == node) {            // still ours? It may have been evicted                order.touch(node);                node.touchedAt = now;            }        } finally {            lock.unlock();        }    }    return node.value;}
touchedAt must be volatile. The check inside the lock is essential, see the next page. memcached had a similar rule for years: an item was moved at most once in 60 seconds.
IdeaWhat is lostWhat is won
Touch at most once in a whileOrder among hot keysMost hits take no lock
tryLock and skipA few touches under loadNobody waits for recency
A reference bit (clock)All but one bit of recencyA read is one write to the entry itself
Sample at evictionSometimes a younger victimNo list at all

When reads truly only read, a read and write lock is right. How it works and when it starves writers is on read and write lock.

The interviewer says: use a ReadWriteLock, caches are 90 percent reads.

BreaksAgree, and put get under the read lock
How
It looks like the textbook.
Limit
Readers write pointers.
Choose when
Never.
WorksExplain, and use one lock
How
"A hit moves a node, so it needs the exclusive lock anyway."
Limit
No parallel reads.
Choose when
Strict LRU.
StrongExplain, then relax the order
How
Reads take no lock, recency is recorded cheaply and applied later.
Limit
Approximate LRU. Say so.
Choose when
Read load that one lock cannot carry.