LRU Cache (Thread Safe)

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-01

Problem Statement

Design a lru cache


Follow up:

1.Make it thread safe


Solution

Designing lru cache is a classical problem.


✅ Algorithm (Using HashMap + Doubly Linked List)

1.Doubly Linked List Nodes store key-value pairs.
2.HashMap maps keys to nodes in the list.
3.When a key is accessed (get or put):
•Move its node to the head (most recently used).
4.When the cache exceeds capacity:
•Remove the tail node (least recently used).
•Delete the key from the map.



Java code

1import java.util.*; 2 3class LRUCache { 4 class Node { 5 int key, value; 6 Node prev, next; 7 Node(int k, int v) { key = k; value = v; } 8 } 9 10 private final int capacity; 11 private Map<Integer, Node> map = new HashMap<>(); 12 private Node head = new Node(0, 0); // dummy head 13 private Node tail = new Node(0, 0); // dummy tail 14 15 public LRUCache(int capacity) { 16 this.capacity = capacity; 17 head.next = tail; 18 tail.prev = head; 19 } 20 21 public int get(int key) { 22 if (!map.containsKey(key)) return -1; 23 Node node = map.get(key); 24 remove(node); 25 insertToHead(node); 26 return node.value; 27 } 28 29 public void put(int key, int value) { 30 if (map.containsKey(key)) { 31 remove(map.get(key)); 32 } 33 if (map.size() == capacity) { 34 Node lru = tail.prev; 35 remove(lru); 36 map.remove(lru.key); 37 } 38 Node node = new Node(key, value); 39 insertToHead(node); 40 map.put(key, node); 41 } 42 43 private void remove(Node node) { 44 node.prev.next = node.next; 45 node.next.prev = node.prev; 46 } 47 48 private void insertToHead(Node node) { 49 node.next = head.next; 50 node.prev = head; 51 head.next.prev = node; 52 head.next = node; 53 } 54}


Follow-up (Thread-Safety):

One simple way to make the LRU Cache thread-safe is to use a single lock that synchronizes access to both the HashMap and the linked list. However, this approach serializes all operations, which can severely impact performance in a multithreaded environment due to contention.

A more scalable solution is to partition the cache into multiple smaller LRU caches, each with its own lock. This way, concurrent access to different partitions can proceed without blocking, improving throughput. This technique is similar to sharding and is often used in high-concurrency scenarios.

There are multiple ways to design a thread-safe LRU cache, and the best approach can depend on the specific use case or the expectations of the interviewer. It’s important to discuss trade-offs such as simplicity vs. performance and to tailor the solution to the problem context.

Comments