Cache with eviction
An in-process cache with a fixed capacity, O(1) get and put, pluggable eviction policy, per-entry TTL, and safety under concurrent access.
Which structure gives O(1) get, O(1) put, and O(1) LRU eviction?
- Sorted array of entries by access time
- HashMap plus a doubly linked list
- TreeMap keyed by timestamp
- Priority queue of access times
The map gives O(1) lookup to a node; the doubly linked list moves that node to the head in O(1) and evicts the tail in O(1). A heap is O(log n) and a sorted structure is worse. This is the canonical answer and interviewers expect the mechanism, not the name.
Capacity is 1000 and a batch job reads a million distinct keys once each. What happens under LRU, and what fixes it?
- Nothing; LRU handles it
- The hot working set is evicted by one-time reads; LFU or a scan-resistant policy fixes it
- The cache grows unbounded
- Reads become O(n)
A single sequential scan flushes everything genuinely hot, because every one-time key looks recent. LFU, or a segmented policy like LRU-K or ARC that requires a second access before promotion, resists this.
Assign each responsibility.
- Expose get, put and remove
- Cache
- Choose which entry to discard when full
- EvictionPolicy
- Hold key, value, expiry and list pointers
- EntryNode
- Decide whether an entry is stale on read
- ExpiryChecker
- Record the access that reorders recency
- EvictionPolicy
Separating eviction from the cache is what lets LRU and LFU coexist without editing the cache. Expiry is deliberately separate from eviction: TTL is about correctness, eviction is about capacity, and conflating them means a stale entry survives simply because it is popular.
Two threads call get on the same key while a third evicts it. Cheapest correct approach?
- synchronized on the whole cache
- Lock striping or a concurrent map with per-entry locking
- No locking; reads are safe
- Copy the cache on every write
A single global lock serialises every operation and destroys the throughput the cache existed to provide. Striping shards the lock by key hash so unrelated keys never contend, which is exactly how production concurrent maps work.