Design an LRU cache
medium 85 minDesign an in-memory Least Recently Used cache with O(1) lookups, updates and evictions.
Watch lesson4:49
Deep dives
Compare the options before you open them, then say which you would pick.
Where they go next, and your first sentence
| They ask | You begin |
|---|---|
| Many threads? | "A hit writes, so one exclusive lock around whole methods." |
| Faster than that? | "Either split the keys or delay the touches. Both cost exact order." |
| Old data? | "Expiry is not eviction. A layer with a deadline and a clock." |
| Big values? | "The limit becomes a weight, if becomes while." |
| Loading? | "One future for each key in flight, and no lock during the load." |
| Another policy? | "Four events: added, used, removed, victim." |
| Many machines? | "A ring chooses the owner. Each server keeps its own order." |
| How do you test it? | "Against a slow list that is obviously right." |
Concurrency tools, one line each
| Tool | Here |
|---|---|
| Mutex, synchronized | The default. Map and list are one state |
| Read and write lock | Only for an approximate order |
| Concurrent map | Lookup without a lock, then check the node again |
| tryLock | Skip a touch, never a write |
| Atomic, LongAdder | Counters. They do not protect the list |
| Future | One result for many waiting callers |