Thread-Safe LRU Cache
HardConcurrencyLRU CacheReadWriteLockConcurrentHashMapDoubly Linked ListThread Safety
Problem Statement
Design a thread-safe LRU (Least Recently Used) Cache that supports O(1) amortized get and put operations under concurrent access from multiple threads.
class ThreadSafeLRUCache<K, V> {
public ThreadSafeLRUCache(int capacity) {}
public V get(K key) {} // Returns null if absent; marks as recently used
public void put(K key, V value) {} // Inserts; evicts LRU entry if at capacity
public int size() {}
public void evict(K key) {} // Manual eviction
}
Key Entities
- HashMap: O(1) key → node lookup.
- Doubly Linked List: Maintains recency order (head = MRU, tail = LRU).
- ReentrantReadWriteLock: Allows concurrent reads, exclusive writes.
- Node: Holds key, value, prev, next pointers.
Requirements
get()andput()must be O(1) amortized.- Thread-safe — concurrent
get()calls from multiple readers are allowed simultaneously. put()acquires a write lock ensuring exclusive access.- When capacity is exceeded, the least recently used entry is evicted.
- Optional: Add TTL (time-to-live) per entry.
Asked at: Amazon, Google, Microsoft, Facebook, Uber, LinkedIn, Apple, DoorDash
!Constraints
- 1 ≤ capacity ≤ 3000
- Keys and values are non-null objects.
- Concurrent readers must not block each other.
- A writer (put/evict) must block all readers.
- get() must update recency order (move to head) — this requires a write lock or careful design.
Output
Run or submit your code to see output here.