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

Deep dives

Compare the options before you open them, then say which you would pick.

Where they go next, and your first sentence

They askYou 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

ToolHere
Mutex, synchronizedThe default. Map and list are one state
Read and write lockOnly for an approximate order
Concurrent mapLookup without a lock, then check the node again
tryLockSkip a touch, never a write
Atomic, LongAdderCounters. They do not protect the list
FutureOne result for many waiting callers

More on