LLD

Full Designs

LRU Cache

A weak answer reaches for a LinkedHashMap and stops. We build the cache the interviewer is asking about: a hash map and our own doubly linked list for constant-time reads and writes, an eviction rule that can change, entries that expire, listeners that hear about every eviction, and one lock that keeps it all correct under many threads.

"Design an LRU cache" sounds like a data structure question. LRU means least recently used: when the cache is full, the entry nobody has touched for longest leaves first. A weak answer writes new LinkedHashMap<>(16, 0.75f, true), overrides one method, and stops. That code works, and it hides every part the interviewer wanted to talk about.

The interviewer wants to see the mechanism. How do a read and a write each take a fixed number of steps, whatever the size? What moves when a key is read? Which entry goes when the cache is full, and what if that rule changes? What happens when two threads write the same key at once, and who gets told when an entry is thrown out?

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

The cache at a glance
A caller asks the Cache for a key (1). Under the cache's lock, the map finds the entry and the Clock says whether it has expired (2). The eviction policy moves the key to the front of its list (3). When a new key arrives and the cache is full, the policy names the key at the back of its list, and the cache removes it (4). After the lock is released, the listeners hear which entry left and why (5).A caller asks the Cache for a key (1). Under the cache's lock, the map finds the entry and the Clock says whether it has expired (2). The eviction policy moves the key to the front of its list (3). When a new key arrives and the cache is full, the policy names the key at the back of its list, and the cache removes it (4). After the lock is released, the listeners hear which entry left and why (5).
A map finds the value. A list keeps the order. A lock keeps them in step. A caller asks the Cache for a key (1). Under the cache's lock, the map finds the entry and the Clock says whether it has expired (2). The eviction policy moves the key to the front of its list (3). When a new key arrives and the cache is full, the policy names the key at the back of its list, and the cache removes it (4). After the lock is released, the listeners hear which entry left and why (5).

Ask before you design

The question is vague on purpose. Each question below changes the code, and the right-hand column says how.

QuestionWhat we assumeWhat it changes
What are the keys and values?Any type. A null key or value is refusedA generic Cache<K, V>, and a null check in every method
What is the capacity measured in?The number of entriesAn int capacity; size is a count, not bytes
Does a read count as a use?YesEvery hit changes the order, so even a read writes to the cache
Which entry goes when the cache is full?The least recently used one, but the rule may changeAn EvictionPolicy interface, with LRU and first in, first out (FIFO) behind it
Does writing a stored key count as a use?Yes, and it never evicts anythingput looks for the key before it makes room
Do entries expire?Optionally, after a time to live counted from the writeA Clock we can control, and an expiry check on every read
Does anyone need to know when an entry leaves?Yes, for example to count evictions or close a fileA listener interface, told after the lock is released
Do many threads use the cache at once?YesOne lock around the map, the list and the counts
Does the cache fetch a missing value itself?No, the caller puts itNo loader; it comes back as a follow-up

The question about reads matters most. If a read counts as a use, every get that finds its key moves it in the list, so reads change the cache. That one answer decides how the cache is locked.

Requirements

Functional:

  1. get(key) returns the value if the key is stored and has not expired, and marks the key as just used. A missing or expired key returns nothing.
  2. put(key, value) stores the value and marks the key as just used. A new key in a full cache first evicts one entry, chosen by the eviction rule, so the cache never holds more than its capacity. Writing a stored key replaces its value and evicts nothing.
  3. remove(key) deletes the entry.
  4. get and put take a fixed number of steps on average, whatever the size, as a hash map does.
  5. With a time to live, an entry is never returned at or after its deadline. The deadline is counted from the last write.
  6. Listeners hear about every entry that leaves because the cache was full or because it expired.
  7. The cache counts hits, misses, evictions and expirations.

Out of scope: sizing by bytes, fetching missing values from a database, writing changes through to one, a cache shared by many servers, and refreshing entries before they expire. We come back to these at the end, because each is a natural follow-up, and a design that bends towards them is part of the answer.

Everything lives in memory, which is what a cache is for.

What the code itself must handle:

  • Many threads at once. get, put and remove are called from many threads, often on the same keys.
  • A rule that changes. Some caches want LRU, some want FIFO, and the cache class should not change for that.
  • Time. Expiry must be testable, so the code takes a Clock and never reads the system time itself.

Finding the classes

A common way to start is to read the requirements and pick out the nouns. Most nouns become classes. Some do not, and dropping them is as much a part of the design as keeping the others.

From nouns to classes
The cache becomes the Cache class, and an entry and the counts become records. The recency order becomes a list inside the eviction policy, and the eviction rule an interface. The time to live and the capacity become CacheSettings, the reason an entry left an enum, and the listener an interface. Three nouns are dropped. A timer is replaced by checking the clock on each read. A thread is a caller. A byte size is out of scope.The cache becomes the Cache class, and an entry and the counts become records. The recency order becomes a list inside the eviction policy, and the eviction rule an interface. The time to live and the capacity become CacheSettings, the reason an entry left an enum, and the listener an interface. Three nouns are dropped. A timer is replaced by checking the clock on each read. A thread is a caller. A byte size is out of scope.
Most nouns become classes. The timer does not. The cache becomes the Cache class, and an entry and the counts become records. The recency order becomes a list inside the eviction policy, and the eviction rule an interface. The time to live and the capacity become CacheSettings, the reason an entry left an enum, and the listener an interface. Three nouns are dropped. A timer is replaced by checking the clock on each read. A thread is a caller. A byte size is out of scope.

The timer needs the most thought. Entries with a time to live have to disappear at some point, and something has to make that happen.

Decision

Should each entry run its own timer?

A timer for every entry, which removes it when time is up

The cache is always exact. But a cache of a million entries runs a million timers, each one a task in a scheduler, and each one takes the cache's lock when it fires. Tests have to wait for real time to pass.

No timer: a read checks the clock, and a sweep cleans up the restOur pick

get compares the entry's deadline with the clock and treats an expired entry as missing. evictExpired walks the cache for a job to call now and then. The cost is that an expired entry nobody reads takes a slot until the sweep, an eviction or a read reaches it. It is never returned, but while it waits, a full cache can evict a live key that a reader still wanted.

Data or behaviour?

Some classes only carry data and never change once created. In Java these are records. A record is a class whose fields are fixed when it is created and which gets equals, hashCode and toString without writing them.

cache/Entry.javalines 5–11 of 11
/** A stored value and the moment it expires; expiresAt is null when it never does. */record Entry<V>(V value, Instant expiresAt) {     boolean isExpired(Instant now) {        return expiresAt != null && !now.isBefore(expiresAt);    }}

An Entry is a value and the moment it expires, or null when the cache has no time to live. It is package-private, because only the cache uses it. CacheStats is a record too: the counts, read together under the lock, so a caller never sees hits from one moment and misses from another.

The class diagram

The classes and how they connect
Cache owns its entries and uses CacheSettings, one EvictionPolicy, every EvictionListener and one Clock. LruPolicy and FifoPolicy implement EvictionPolicy, and each owns a map from key to Node and a DoublyLinkedList, which links the nodes. Cache creates a Removal for each entry that leaves, and a CacheStats when asked for the counts. Entry, Removal and CacheStats are records, and RemovalCause is an enum.Cache owns its entries and uses CacheSettings, one EvictionPolicy, every EvictionListener and one Clock. LruPolicy and FifoPolicy implement EvictionPolicy, and each owns a map from key to Node and a DoublyLinkedList, which links the nodes. Cache creates a Removal for each entry that leaves, and a CacheStats when asked for the counts. Entry, Removal and CacheStats are records, and RemovalCause is an enum.
Cache owns the values and the lock. The policy owns the order. Cache owns its entries and uses CacheSettings, one EvictionPolicy, every EvictionListener and one Clock. LruPolicy and FifoPolicy implement EvictionPolicy, and each owns a map from key to Node and a DoublyLinkedList, which links the nodes. Cache creates a Removal for each entry that leaves, and a CacheStats when asked for the counts. Entry, Removal and CacheStats are records, and RemovalCause is an enum.

The classes fall into three groups:

  • Data: Entry, CacheStats and Removal are records, and RemovalCause is an enum. CacheSettings is a small class that checks its own values.
  • The core: Cache, which owns the values, the counts and the lock. DoublyLinkedList and Node are the order inside a policy, and nothing outside the policy package can touch them.
  • Rules and outside code: EvictionPolicy with LruPolicy and FifoPolicy, EvictionListener for whoever wants to hear about evictions, and Clock from java.time.

The rest of the article builds these one at a time.

Building it

The list that keeps the order

LRU needs two things in a fixed number of steps: find a key, and move it to the front of an order. A HashMap finds a key. For the order, an array would need to shift every element to move one. So the order is a doubly linked list. Each node points to the node before it and the node after it, so a node can be taken out and put back without walking the list.

policy/DoublyLinkedList.javalines 11–42 of 67
final class DoublyLinkedList<K> {    private final Node<K> head = new Node<>(null);    private final Node<K> tail = new Node<>(null);    private int size;     DoublyLinkedList() {        head.next = tail;        tail.prev = head;    }     /** Puts node right after head: the front of the list. */    void addFirst(Node<K> node) {        node.prev = head;        node.next = head.next;        head.next.prev = node;        head.next = node;        size++;    }     /** Takes node out, joining its neighbours to each other. */    void remove(Node<K> node) {        node.prev.next = node.next;        node.next.prev = node.prev;        node.prev = null;        node.next = null;        size--;    }     void moveToFront(Node<K> node) {        remove(node);        addFirst(node);    }

addFirst writes four links: the new node's two, the old first node's back link, and the head's forward link. remove joins the node's two neighbours to each other, then clears the node's own links. moveToFront is the two together. None of them loops, so each takes the same few steps for a list of three or three million.

Moving a key to the front
The list holds C, B and A between two sentinel nodes, head and tail. To move B to the front, remove() joins C and A to each other (1, 2). addFirst() then points B back at head and forward at C (3, 4), points C back at B (5), and points head forward at B (6). The back of the list, A, is the least recently used key.The list holds C, B and A between two sentinel nodes, head and tail. To move B to the front, remove() joins C and A to each other (1, 2). addFirst() then points B back at head and forward at C (3, 4), points C back at B (5), and points head forward at B (6). The back of the list, A, is the least recently used key.
A read of B changes six links, and nothing is copied. The list holds C, B and A between two sentinel nodes, head and tail. To move B to the front, remove() joins C and A to each other (1, 2). addFirst() then points B back at head and forward at C (3, 4), points C back at B (5), and points head forward at B (6). The back of the list, A, is the least recently used key.
Decision

Use Java's LinkedHashMap, or write the list?

LinkedHashMap with access order, and removeEldestEntry

It is a few lines and well tested. It is also a fine choice in production. But in an interview it answers "how does LRU work?" with "the library knows", and the interviewer cannot see whether you know why a read is cheap.

Write the list ourselves, and say that LinkedHashMap does the sameOur pick

The list is one short class, and every step is on the page. Saying that LinkedHashMap keeps the same kind of list inside shows that you know both, and that you would use the library at work. The hidden cost is ours to test: a single wrong link breaks the order.

head and tail are sentinel nodes: nodes that hold no key and never leave. The real nodes always sit between them.

Decision

Sentinel nodes, or null checks at the ends?

head and tail are the first and last real nodes, and may be null

It saves two small objects. But every method needs cases for an empty list, a list of one, the first node and the last node. Those cases are where linked list bugs live.

Two sentinel nodes that never leaveOur pick

Every real node has a node before it and a node after it, so remove and addFirst have no special cases. An empty list is head pointing at tail. The cost is two nodes per list and remembering that last() must not return head.

The eviction rule

The list knows nothing about LRU. LRU is a rule about when keys move, and FIFO is a different rule over the same list. So the rule sits behind an interface:

policy/EvictionPolicy.javalines 12–28 of 28
public interface EvictionPolicy<K> {     /** A key the policy does not know yet has been stored. */    void recordInsert(K key);     /** A stored key was read, or its value replaced. */    void recordAccess(K key);     /** A stored key has left the cache, for any reason. */    void recordRemoval(K key);     /** The key to evict next. Called only when the policy knows at least one key. */    K victim();     /** Every key the policy knows, the next to be evicted first. */    List<K> evictionOrder();}

The cache tells the policy about every key that comes in, is used or goes out, and asks it for a victim when it is full. LruPolicy keeps a map from key to node beside its list, so it can find a key's node without walking:

policy/LruPolicy.javalines 11–44 of 53
public final class LruPolicy<K> implements EvictionPolicy<K> {    private final Map<K, Node<K>> nodes = new HashMap<>();    private final DoublyLinkedList<K> order = new DoublyLinkedList<>();     @Override    public void recordInsert(K key) {        if (nodes.containsKey(key)) {            throw new IllegalStateException("already known: " + key);        }        Node<K> node = new Node<>(key);        nodes.put(key, node);        order.addFirst(node);    }     @Override    public void recordAccess(K key) {        order.moveToFront(nodeOf(key));    }     @Override    public void recordRemoval(K key) {        order.remove(nodeOf(key));        nodes.remove(key);    }     @Override    public K victim() {        return order.last().key;    }     @Override    public List<K> evictionOrder() {        return order.keysFromBack();    }

recordAccess moves the node to the front. victim is the node at the back. FifoPolicy is the same code with one method changed, because in FIFO a read moves nothing:

policy/FifoPolicy.javalines 25–28 of 53
    @Override    public void recordAccess(K key) {        nodeOf(key);    }

The two rules cost different things. LRU rewrites six links on every hit, because a hit moves a key; a hit on the key already at the front ends with the links it started with. FIFO writes nothing on a read, so a key read a thousand times still leaves when its turn comes, which LRU would not do while the key keeps being read. LRU suits data where recent use predicts the next use, such as product pages. FIFO suits data that goes stale with age whatever its use. A frequency-based rule, least frequently used (LFU), keeps a count per key; its constant-time version keeps a list of keys for each count, which is more code and more memory per key.

Same steps, different victim
Both caches hold three entries. Each stores P1, P2 and P3, then reads P1, then stores P4. LRU moved P1 to the front when it was read, so P2 is at the back and leaves. FIFO did not move P1, so P1, the first one in, leaves.Both caches hold three entries. Each stores P1, P2 and P3, then reads P1, then stores P4. LRU moved P1 to the front when it was read, so P2 is at the back and leaves. FIFO did not move P1, so P1, the first one in, leaves.
P1 was just read. LRU keeps it. FIFO drops it. Both caches hold three entries. Each stores P1, P2 and P3, then reads P1, then stores P4. LRU moved P1 to the front when it was read, so P2 is at the back and leaves. FIFO did not move P1, so P1, the first one in, leaves.
Decision

Where does the recency order live?

In the cache's own nodes: one map from key to a node that holds the value

This is the shortest LRU: one map, one list, one lookup per read. But the order rule is welded into the cache, so FIFO or LFU means a second cache class.

Behind the eviction policy, with its own map from key to nodeOur pick

The cache keeps values, deadlines and counts. The policy keeps the order. Any rule fits behind the interface. The cost is a second map. Each key is stored in two hash maps, so every call does more hash work: a hit looks the key up twice, a new key is added to both maps, and an eviction removes from both. Both maps also grow as the cache fills. On average each call still takes a fixed number of steps.

The cache and its lock

Cache holds the values in a HashMap of entries, the policy, the clock and the counts, all guarded by one private lock:

cache/Cache.javalines 22–34 of 209
public final class Cache<K, V> {    private final CacheSettings settings;    private final EvictionPolicy<K> policy;    private final Clock clock;    private final Map<K, Entry<V>> entries = new HashMap<>();    private final List<EvictionListener<K, V>> listeners = new CopyOnWriteArrayList<>();    private final Object lock = new Object();     private long hits;    private long misses;    private long evictions;    private long expirations;    private long listenerFailures;

The lock is a private object, not this, so code outside the class cannot hold it and stall every reader.

Reading a key

cache/Cache.javalines 47–69 of 209
    /** The value for key, if it is stored and has not expired. A hit counts as a use. */    public Optional<V> get(K key) {        Objects.requireNonNull(key, "key");        Removal<K, V> expired;        synchronized (lock) {            Entry<V> entry = entries.get(key);            if (entry == null) {                misses++;                return Optional.empty();            }            if (!entry.isExpired(clock.instant())) {                policy.recordAccess(key);                hits++;                return Optional.of(entry.value());            }            removeEntry(key);            expirations++;            misses++;            expired = new Removal<>(key, entry.value(), RemovalCause.EXPIRED);        }        tellListeners(List.of(expired));        return Optional.empty();    }

get takes the lock, finds the entry, and asks the clock whether the entry has expired. A live entry tells the policy it was used, counts a hit and returns its value. An expired entry is removed from the map and the policy, counted as an expiration and a miss, and reported to listeners once the lock is released. The caller cannot tell an expired entry from a missing one, and that is intended.

The check is !now.isBefore(expiresAt), so an entry written at 10:00 with ten minutes to live is gone at exactly 10:10, not a moment after.

Writing a key

cache/Cache.javalines 71–106 of 209
    /**     * Stores value under key. A new key in a full cache first makes room.     * Replacing a live value tells no listener. An expired value is removed and reported as     * EXPIRED first, and the new value then goes in as a new key.     */    public void put(K key, V value) {        Objects.requireNonNull(key, "key");        Objects.requireNonNull(value, "value");        List<Removal<K, V>> removed = new ArrayList<>(1);        try {            synchronized (lock) {                Instant now = clock.instant();                Entry<V> fresh = new Entry<>(value, settings.expiresAt(now));                Entry<V> old = entries.get(key);                if (old != null && old.isExpired(now)) {                    // A dead entry leaves first, so the new value goes in as a new key.                    removeEntry(key);                    expirations++;                    removed.add(new Removal<>(key, old.value(), RemovalCause.EXPIRED));                    old = null;                }                if (old != null) {                    policy.recordAccess(key);                    entries.put(key, fresh);                    return;                }                if (entries.size() == settings.capacity()) {                    removed.add(evictOne(now));                }                policy.recordInsert(key);                entries.put(key, fresh);            }        } finally {            tellListeners(removed);        }    }

put first asks whether the key is already stored. If it is, the new value replaces the old one, the policy hears it was used, and nothing is evicted. A live value that is replaced is not reported to listeners, because the caller chose to replace it. An old value that had already expired is removed first, counted and reported as EXPIRED, so a listener that closes files still hears about it. The new value then goes in as a new key, so under FIFO it joins the back of the queue instead of keeping the dead entry's place. Only a new key in a full cache calls evictOne, which makes room before the new key goes in.

Decision

Make room before storing, or store and then trim?

Store the new key, then evict while the size is over capacity

It is short. But the policy hears about the new key before it picks a victim, so a rule that favours old keys could pick the key just written. A write to a stored key also needs care, or it trims an entry for no reason.

Check for the key first, then evict one entry if the cache is full, then storeOur pick

The size never goes over capacity, even inside the lock, and the victim is always a key that was already there. A write to a stored key never costs another key its place. The cost is one lookup of the key before the work.

cache/Cache.javalines 173–193 of 209
    /** Asks the policy for a victim and removes it. Called under the lock with the cache full. */    private Removal<K, V> evictOne(Instant now) {        K victim = policy.victim();        Entry<V> entry = entries.get(victim);        if (entry == null) {            throw new IllegalStateException("the policy chose a key the cache does not hold: " + victim);        }        removeEntry(victim);        if (entry.isExpired(now)) {            expirations++;            return new Removal<>(victim, entry.value(), RemovalCause.EXPIRED);        }        evictions++;        return new Removal<>(victim, entry.value(), RemovalCause.CAPACITY);    }     /** The policy goes first: if it throws, the map has not changed. */    private void removeEntry(K key) {        policy.recordRemoval(key);        entries.remove(key);    }

evictOne asks the policy for the victim and checks that the cache holds it. A policy with a bug could name a key the cache never stored, and the cache refuses that before anything changes. removeEntry tells the policy first and changes the map second, so if the policy throws, the map is as it was. If the victim had already expired, it is counted and reported as EXPIRED, not as an eviction, so the counts say why each entry left. If the policy then refuses the new key, put throws with the victim already gone and the new key not stored, and listeners still hear about the victim. The cache cannot undo that eviction, because the policy has no way to put the victim back where it was in the order.

There are two kinds of error, and each one says what it is for. IllegalArgumentException and NullPointerException are for a programmer: a capacity of 0, a null key, or a policy that already holds keys. The cache makes its policy from a supplier: LruPolicy::new gives each cache its own policy, and the constructor refuses a policy that already holds keys. IllegalStateException means the policy has a bug. A miss is not an error at all: it is an empty Optional.

Entries that expire

The time to live is part of the settings, checked when they are made:

cache/CacheSettings.javalines 28–35 of 49
    /** The same capacity, with every entry expiring timeToLive after it is written. */    public CacheSettings withTimeToLive(Duration timeToLive) {        Objects.requireNonNull(timeToLive, "timeToLive");        if (timeToLive.isNegative() || timeToLive.isZero() || timeToLive.compareTo(MAX_TIME_TO_LIVE) > 0) {            throw new IllegalArgumentException("timeToLive must be above zero and at most 365 days, got " + timeToLive);        }        return new CacheSettings(capacity, timeToLive);    }

A time to live must be above zero and at most 365 days. The upper limit keeps now.plus(timeToLive) far from the largest Instant, where adding would overflow. A cache without a time to live stores null as each entry's deadline, and its entries only leave when the cache is full or when they are removed.

Decision

Does a read extend an entry's life?

Yes: the deadline moves on every read

An entry that is used often never expires. But the time to live then says "unused for ten minutes", not "older than ten minutes", and a price read every second would never be refreshed from its source.

No: the deadline is counted from the last writeOur pick

The time to live bounds how stale a value can be, which is what it is usually for. A read does not touch the deadline; a write starts it again. Expiring after ten minutes without a read is a different rule, and it is a row in the follow-up table.

An expired entry nobody reads stays until something reaches it. evictExpired is for a job that calls it now and then:

cache/Cache.javalines 120–139 of 209
    /** Removes every expired entry, for a job to call now and then. Returns how many went. */    public int evictExpired() {        List<Removal<K, V>> removed = new ArrayList<>();        try {            synchronized (lock) {                Instant now = clock.instant();                for (K key : policy.evictionOrder()) {                    Entry<V> entry = entries.get(key);                    if (entry.isExpired(now)) {                        removeEntry(key);                        expirations++;                        removed.add(new Removal<>(key, entry.value(), RemovalCause.EXPIRED));                    }                }            }        } finally {            tellListeners(removed);        }        return removed.size();    }

It walks the policy's order, removes every entry whose deadline has been reached, and reports them in that order. It holds the lock for the whole walk, so it takes time in proportion to the size of the cache. That is short for a few thousand entries. A cache of millions would want to sweep in batches.

Telling listeners

Some callers need to know when an entry leaves: to count evictions, or to close a file the value held. A listener hears the key, the value and the reason:

cache/Cache.javalines 195–208 of 209
    /** Called with no lock held. A listener that throws is counted and the rest still hear. */    private void tellListeners(List<Removal<K, V>> removed) {        for (Removal<K, V> removal : removed) {            for (EvictionListener<K, V> listener : listeners) {                try {                    listener.onRemoval(removal.key(), removal.value(), removal.cause());                } catch (RuntimeException e) {                    synchronized (lock) {                        listenerFailures++;                    }                }            }        }    }
Decision

Tell listeners inside the lock, or after it?

Inside the lock, as each entry is removed

The listeners hear about evictions in exactly the order they happened. But a listener is outside code. If it writes to a slow log, every get on the cache waits for that log. If it waits for another thread that calls the cache, the two wait on each other for ever.

After the lock is released, from a list built under itOur pick

put, get and evictExpired collect each Removal under the lock and call tellListeners once it is released. A slow listener slows only the thread that triggered the eviction. A listener may call back into the cache, even to put a different key, because no lock is held. The cost is order: two threads that each evict an entry can tell their listeners in either order. A listener that puts every evicted key straight back evicts another key, is called again, and recurses until the thread runs out of stack. The StackOverflowError can cut the innermost put off half way through the policy's own update, leaving the map and the policy out of step for good. So a listener may read the cache, but it must never put back the key it was told about.

Decision

What happens when a listener throws?

The exception goes back to the caller of put or get

The caller sees the problem. But the write has already happened, so the caller is told "failed" about a write that worked, and the listeners after the broken one never hear.

Count it, and carry on with the next listenerOur pick

A broken metrics listener cannot break the cache. Every other listener still hears, and stats().listenerFailures() shows that something is wrong. A real application would also log it. An Error, such as running out of memory, is not caught and still goes to the caller.

Many threads, one cache

A cache is shared by every thread that needs its data, and many of them read and write the same keys at once.

Two writes of one new key
On the left, there is no lock. Thread A asks whether P9 is stored and finds it is not. Before A stores it, thread B asks the same and gets the same answer. Both tell the policy about a new key, and the second is refused, or the list gets P9 twice. On the right, the check and the store run under the cache's lock, so B waits, finds P9 stored, and replaces its value.On the left, there is no lock. Thread A asks whether P9 is stored and finds it is not. Before A stores it, thread B asks the same and gets the same answer. Both tell the policy about a new key, and the second is refused, or the list gets P9 twice. On the right, the check and the store run under the cache's lock, so B waits, finds P9 stored, and replaces its value.
Without a lock, checking for a key and storing it are two steps that can interleave. On the left, there is no lock. Thread A asks whether P9 is stored and finds it is not. Before A stores it, thread B asks the same and gets the same answer. Both tell the policy about a new key, and the second is refused, or the list gets P9 twice. On the right, the check and the store run under the cache's lock, so B waits, finds P9 stored, and replaces its value.

Every method that reads or changes the map, the policy or the counts takes the one lock. A read or a write holds it for a few map lookups and link writes. evictExpired and evictionOrder hold it while they walk the whole list. Outside code also runs under it: the clock read, the policy, and the keys' own hashCode and equals, which the maps call.

The project includes a check, demo/RaceCheck.java. Sixteen threads make 100,000 calls each on a cache of 64 entries, spread over 256 keys. Six calls in ten are reads, and nearly all the rest are writes, with a removal now and then. Each value is its key times 1,000 plus a little, so a value can be traced back to its key.

$ java demo.RaceCheck
16 threads, 1,600,000 operations, on a cache of 64 entries and 256 keys
size at the end: 64 of 64
times a thread saw more than 64 entries: 0
values returned for the wrong key: 0
keys in the eviction order: 64, duplicates: 0
reads made: 960,002, hits plus misses counted: 960,002
evictions counted: 448,161, heard by the listener: 448,161

The size never went over 64, every value came back under its own key, the order holds each key once, and the counts agree with the threads' own counts. We also ran the same check with the lock removed from get, put and remove. Every run we tried stopped almost at once, with an IllegalStateException from the policy or from the cache's victim check, or a NullPointerException inside the list. When we caught those errors and carried on, the list's links broke, with nodes pointing at nothing. The cache grew to about three times its capacity, and in some runs the list's own count went below zero. Most of the hits and misses were never counted. The exact numbers change from run to run, and none of it shows up when one thread tests the cache alone.

Decision

Where does the lock go?

A ReadWriteLock, so that reads can run together

It is the usual answer for a structure that is read far more than it is written. But in LRU a hit moves a key in the list, and a get cannot know in advance whether it will hit, so every get needs the write lock. Nothing runs together, and a read-write lock does more work per call than a plain one. Under FIFO a read moves nothing, but it still counts a hit or a miss and may remove an expired entry, and a read lock cannot be turned into a write lock. A read lock would help only if the counts moved to LongAdders and expiry took the write lock in a separate step.

A ConcurrentHashMap for the values, and a lock on the list only

Lookups in the map run together. But a get must find the entry and move its key as one step, or an eviction can remove the key between the two. The map and the list must change together, so they need the same lock.

Split the cache into segments by the key's hash, each with its own lock

Threads on different segments never wait for each other, which is one way production caches scale; another is to record reads in a buffer and replay them under one lock in batches. But each segment has its own LRU order and its own share of the capacity, so the cache evicts the least recently used entry of a segment, not of the whole cache. That is a fair trade for a busy server, and a follow-up here.

One lock for the whole cache, held only for the map and list workOur pick

The map, the list and the counts always agree, and the rule stays exactly LRU. Each read and write holds the lock for a fixed number of steps, and listeners run after it is released. The cost is that threads take turns, which matters only when the cache is the busiest thing in a program.

The final design

Cache is the core. It owns the values, their deadlines, the counts, the listeners and the one lock. It reaches the order only through EvictionPolicy, and the time only through Clock, so a new eviction rule or a test clock changes nothing in Cache.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Cache carries 1, 5, 6, 7, 8 and 9. DoublyLinkedList carries 2 and 3. LruPolicy carries 4. EvictionPolicy carries a Strategy tag, and EvictionListener carries an Observer tag.The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Cache carries 1, 5, 6, 7, 8 and 9. DoublyLinkedList carries 2 and 3. LruPolicy carries 4. EvictionPolicy carries a Strategy tag, and EvictionListener carries an Observer tag.
Each decision lands on one class. Two interfaces carry a pattern. The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Cache carries 1, 5, 6, 7, 8 and 9. DoublyLinkedList carries 2 and 3. LruPolicy carries 4. EvictionPolicy carries a Strategy tag, and EvictionListener carries an Observer tag.
S.No.The questionWhat we choseWhy
1Should each entry run its own timer?No timer: a read checks the clock, and a sweep cleans up the restAn expired entry is never returned, and no cache runs a million timers
2Use Java's LinkedHashMap, or write the list?Write the list ourselves, and say that LinkedHashMap does the sameEvery step is on the page, and the library stays the choice at work
3Sentinel nodes, or null checks at the ends?Two sentinel nodes that never leaveEvery real node has neighbours, so the list has no special cases
4Where does the recency order live?Behind the eviction policy, with its own map from key to nodeAny rule fits behind the interface, for a second map and more hash work per call
5Make room before storing, or store and then trim?Check for the key first, then evict one entry if the cache is full, then storeThe size never goes over capacity, and a replace never evicts
6Does a read extend an entry's life?No: the deadline is counted from the last writeThe time to live bounds how stale a value can be
7Tell listeners inside the lock, or after it?After the lock is released, from a list built under itA slow or calling-back listener cannot stall the cache
8What happens when a listener throws?Count it, and carry on with the next listenerA broken listener cannot break a write that worked
9Where does the lock go?One lock for the whole cache, held only for the map and list workThe map, the list and the counts always agree, and LRU stays exact

Here is a write of P4 into the full cache from the demo, end to end:

  1. A caller calls put("P4", "Iron"). It checks for nulls with no lock held, so a bad call never waits for the lock. Then it takes the cache's lock and reads the time from the Clock to work out the new entry's deadline.
  2. entries.get finds no entry for P4, and the map holds three entries, so put calls evictOne. The policy is code the cache is given, and it runs under the lock: LruPolicy.victim returns P2, the node at the back of its list.
  3. removeEntry calls LruPolicy.recordRemoval, which unlinks P2's node with DoublyLinkedList.remove, and then removes P2 from the map. Because the policy changes first and the map second, a policy that threw here would leave the map as it was. evictOne counts an eviction and returns a Removal for P2.
  4. LruPolicy.recordInsert puts a node for P4 at the front with addFirst, and put stores the entry in the map. The lock is released as the synchronized block ends.
  5. The finally block calls tellListeners, with no lock held. Each EvictionListener hears that P2 Mixer left for CAPACITY. A listener that threw would be counted and skipped.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

cacheCache.java
package cache; import java.time.Clock;import java.time.Instant;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional;import java.util.concurrent.CopyOnWriteArrayList;import java.util.function.Supplier; import policy.EvictionPolicy; /** * A fixed-size cache. Reads and writes take a fixed number of steps, whatever * the size. When the cache is full, its EvictionPolicy picks the entry to drop. * Safe to use from many threads: one private lock guards the map, the policy * and the counts, and listeners are told after it is released. */public final class Cache<K, V> {    private final CacheSettings settings;    private final EvictionPolicy<K> policy;    private final Clock clock;    private final Map<K, Entry<V>> entries = new HashMap<>();    private final List<EvictionListener<K, V>> listeners = new CopyOnWriteArrayList<>();    private final Object lock = new Object();     private long hits;    private long misses;    private long evictions;    private long expirations;    private long listenerFailures;     /** newPolicy makes this cache's own policy, for example LruPolicy::new. */    public Cache(CacheSettings settings, Supplier<? extends EvictionPolicy<K>> newPolicy, Clock clock) {        this.settings = Objects.requireNonNull(settings, "settings");        Objects.requireNonNull(newPolicy, "newPolicy");        this.policy = Objects.requireNonNull(newPolicy.get(), "the policy supplier returned null");        this.clock = Objects.requireNonNull(clock, "clock");        if (!policy.evictionOrder().isEmpty()) {            throw new IllegalArgumentException("the policy already holds keys; give each cache a new policy");        }    }     /** The value for key, if it is stored and has not expired. A hit counts as a use. */    public Optional<V> get(K key) {        Objects.requireNonNull(key, "key");        Removal<K, V> expired;        synchronized (lock) {            Entry<V> entry = entries.get(key);            if (entry == null) {                misses++;                return Optional.empty();            }            if (!entry.isExpired(clock.instant())) {                policy.recordAccess(key);                hits++;                return Optional.of(entry.value());            }            removeEntry(key);            expirations++;            misses++;            expired = new Removal<>(key, entry.value(), RemovalCause.EXPIRED);        }        tellListeners(List.of(expired));        return Optional.empty();    }     /**     * Stores value under key. A new key in a full cache first makes room.     * Replacing a live value tells no listener. An expired value is removed and reported as     * EXPIRED first, and the new value then goes in as a new key.     */    public void put(K key, V value) {        Objects.requireNonNull(key, "key");        Objects.requireNonNull(value, "value");        List<Removal<K, V>> removed = new ArrayList<>(1);        try {            synchronized (lock) {                Instant now = clock.instant();                Entry<V> fresh = new Entry<>(value, settings.expiresAt(now));                Entry<V> old = entries.get(key);                if (old != null && old.isExpired(now)) {                    // A dead entry leaves first, so the new value goes in as a new key.                    removeEntry(key);                    expirations++;                    removed.add(new Removal<>(key, old.value(), RemovalCause.EXPIRED));                    old = null;                }                if (old != null) {                    policy.recordAccess(key);                    entries.put(key, fresh);                    return;                }                if (entries.size() == settings.capacity()) {                    removed.add(evictOne(now));                }                policy.recordInsert(key);                entries.put(key, fresh);            }        } finally {            tellListeners(removed);        }    }     /** Removes key if it is stored. Listeners are not told: the caller asked for it. */    public boolean remove(K key) {        Objects.requireNonNull(key, "key");        synchronized (lock) {            if (!entries.containsKey(key)) {                return false;            }            removeEntry(key);            return true;        }    }     /** Removes every expired entry, for a job to call now and then. Returns how many went. */    public int evictExpired() {        List<Removal<K, V>> removed = new ArrayList<>();        try {            synchronized (lock) {                Instant now = clock.instant();                for (K key : policy.evictionOrder()) {                    Entry<V> entry = entries.get(key);                    if (entry.isExpired(now)) {                        removeEntry(key);                        expirations++;                        removed.add(new Removal<>(key, entry.value(), RemovalCause.EXPIRED));                    }                }            }        } finally {            tellListeners(removed);        }        return removed.size();    }     public void addListener(EvictionListener<K, V> listener) {        listeners.add(Objects.requireNonNull(listener, "listener"));    }     /** Stops telling listener. Returns false if it was not listening. */    public boolean removeListener(EvictionListener<K, V> listener) {        return listeners.remove(Objects.requireNonNull(listener, "listener"));    }     public int size() {        synchronized (lock) {            return entries.size();        }    }     public int capacity() {        return settings.capacity();    }     /** Every stored key, the next to be evicted first. Expired entries not yet removed are included. */    public List<K> evictionOrder() {        synchronized (lock) {            return policy.evictionOrder();        }    }     public CacheStats stats() {        synchronized (lock) {            return new CacheStats(hits, misses, evictions, expirations, listenerFailures);        }    }     /** Asks the policy for a victim and removes it. Called under the lock with the cache full. */    private Removal<K, V> evictOne(Instant now) {        K victim = policy.victim();        Entry<V> entry = entries.get(victim);        if (entry == null) {            throw new IllegalStateException("the policy chose a key the cache does not hold: " + victim);        }        removeEntry(victim);        if (entry.isExpired(now)) {            expirations++;            return new Removal<>(victim, entry.value(), RemovalCause.EXPIRED);        }        evictions++;        return new Removal<>(victim, entry.value(), RemovalCause.CAPACITY);    }     /** The policy goes first: if it throws, the map has not changed. */    private void removeEntry(K key) {        policy.recordRemoval(key);        entries.remove(key);    }     /** Called with no lock held. A listener that throws is counted and the rest still hear. */    private void tellListeners(List<Removal<K, V>> removed) {        for (Removal<K, V> removal : removed) {            for (EvictionListener<K, V> listener : listeners) {                try {                    listener.onRemoval(removal.key(), removal.value(), removal.cause());                } catch (RuntimeException e) {                    synchronized (lock) {                        listenerFailures++;                    }                }            }        }    }}
Click a class name in the code to open its fileJava · 209 lines · 785 in the project

demo/Main.java runs a shop's cache of its three most used product pages. It shows which entry a full LRU cache drops, the same steps under FIFO, two entries expiring, a listener that throws, and the inputs the cache refuses:

$ java demo.Main
== An LRU cache of 3 products, each entry lives 10 minutes ==
10:00 put P1 Kettle, P2 Mixer, P3 Toaster
      next to go: [P1, P2, P3]
10:01 get P1
      -> Kettle
      next to go: [P2, P3, P1]
10:02 put P4 Iron
      listener: P2 Mixer left (CAPACITY)
      next to go: [P3, P1, P4]
10:03 put P3 Toaster v2, a new value for a stored key
      next to go: [P1, P4, P3]
10:04 get P2
      -> nothing

== The same first four steps with FIFO ==
10:04 put P1 Kettle, P2 Mixer, P3 Toaster
10:04 get P1
      -> Kettle
      next to go: [P1, P2, P3]
10:04 put P4 Iron
      listener: P1 Kettle left (CAPACITY)
      next to go: [P2, P3, P4]

== Time to live, back on the LRU cache ==
10:11 get P1, which was written at 10:00
      listener: P1 Kettle left (EXPIRED)
      -> nothing
10:12 evictExpired()
      listener: P4 Iron left (EXPIRED)
      -> removed 1
      next to go: [P3]

== A listener that throws ==
10:12 put P5 Fan, P6 Heater, P7 Lamp
      listener: P3 Toaster v2 left (CAPACITY)
      next to go: [P5, P6, P7]
10:12 get P7
      -> Lamp

== Inputs the cache refuses ==
refused: IllegalArgumentException: capacity must be at least 1, got 0
refused: IllegalArgumentException: timeToLive must be above zero and at most 365 days, got PT0S
refused: NullPointerException: key
refused: NullPointerException: value

LRU cache counts: 2 hits, 2 misses, 2 evictions, 2 expirations, 1 listener failure
hit rate: 50%

Notice four things in the output. At 10:02 the LRU cache dropped P2, not P1, because P1 had been read a minute earlier, while FIFO dropped P1 for the same steps. At 10:03 a new value for P3 evicted nothing and moved P3 to the end of the order. At 10:11 P1 was gone because it was written at 10:00, though it was read at 10:01, and the sweep at 10:12 removed P4 at exactly its deadline. After a listener started throwing, P7 was still stored, and the counts show one listener failure.

Follow-up questions

After the core design, the interviewer adds requirements to see how the design bends. A good design absorbs most of them in one or two classes. For each one, say which class changes and which do not.

The interviewer asksWhat changesWhat does not
"Evict the least frequently used entry instead."A new LfuPolicy with a count per key and a list of keys for each count.Cache, the lock, the listeners.
"Load a missing value from the database."A loader interface given to Cache, called on a miss. It must be called with no lock held, so two threads can load the same key at once unless Cache also keeps a map of loads in progress.The policies and expiry.
"Expire entries ten minutes after their last read."Entry gets a second deadline, and get replaces the entry with a new deadline on each hit.The policies and the lock.
"Size the cache by bytes, not entries."Cache asks a weigher for each value's size, keeps a running total, and evicts until the new entry fits, which can mean several evictions per put.The policies and the listeners.
"Make it faster for many cores."Cache becomes several segments by the key's hash, each a cache with its own lock and a share of the capacity. LRU is then per segment.The policies, Entry, the listeners.
"Share the cache across servers."The cache moves out of the process into a store such as Redis, which offers LRU eviction and expiry itself. This class becomes a near cache in front of it.The EvictionPolicy interface, for the near cache.
"Write changes through to the database."put calls a writer before or after it stores the value, with no lock held while the database works.The policies and expiry.
"Show how well the cache is doing."Nothing: stats() already counts hits, misses, evictions and expirations, and a listener can count more.Everything.

In most rows the change lands in one class or behind one interface. The loader is the one to think through out loud, because a slow load under the lock would stall every thread.

What the interviewer looks for

Mid-level

A mid-level candidate shows a hash map and a doubly linked list, with get and put that move keys to the front and evict from the back. They explain why each takes a fixed number of steps, and they handle a cache of one entry and a write to a stored key.

Senior

A senior candidate shows everything above and gives the reasons. They use sentinel nodes, put the eviction rule behind an interface, and check for the key before making room. They take a clock for expiry, and they explain why a read lock does not help when a read moves a key.

Staff+

A staff candidate leads the conversation through the trade-offs without being asked. They tell listeners after the lock is released and say what that costs in order. They explain segmented caches and approximate LRU for many cores, and they name the trap in a loading cache: two threads loading the same key, or a load held under the lock.

Common mistakes

  • Moving a key by searching the list. A list search takes longer as the cache grows, so get is no longer a fixed number of steps.
  • Evicting on a write to a stored key. A cache that is full loses an entry for nothing.
  • A ReadWriteLock for an LRU cache. Every hit moves a key, so every get needs the write lock.
  • Calling listeners under the lock. One slow listener stalls every reader, and a listener that calls back from another thread can wait for ever.
  • Reading the system time inside the cache. Expiry then cannot be tested without waiting for real minutes to pass.
  • Treating LinkedHashMap as the whole answer. It is fine in production, but the interviewer asked how it works.

Summary

  • Ask before designing. Whether a read counts as a use decides how the cache is locked.
  • Find a key with a hash map, and keep the order in a doubly linked list with two sentinel nodes, so a read and a write each take a fixed number of steps.
  • Put the eviction rule behind an interface. LRU moves a key on every read, and FIFO never does.
  • Check for the key before making room, so the size never goes over capacity and a replace never evicts.
  • Count the time to live from the last write, check it on every read with an injected clock, and sweep the rest from a job.
  • Tell listeners after the lock is released, and count a listener that throws instead of failing the write.
  • Guard the map, the list and the counts with one lock, held only for a few steps.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.