LRU Cache in Java: Implementation Guide and Examples
In this article
Implementing a Least Recently Used (LRU) cache in Java allows you to store a limited number of items in memory and automatically discard the least recently accessed item when the capacity is reached. This is critical for optimizing application performance by keeping frequently used data readily available while preventing memory overflow. The most efficient way to achieve this in Java is by leveraging a combination of a HashMap for constant-time lookups and a doubly linked list to maintain the order of access.
What You'll Need
- Java Development Kit (JDK) 8 or higher.
- An Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code.
- A basic understanding of Java Collections Framework, specifically Map and LinkedList.
Step-by-Step
- Choose Your Implementation Strategy: You have two primary paths. You can use the built-in
LinkedHashMapclass, which is designed specifically for this purpose, or you can build a custom implementation using aHashMapand a manual doubly linked list for deeper control and better performance in high-concurrency scenarios. - Implement Using LinkedHashMap (The Fast Way):
The
LinkedHashMapclass provides a protected method calledremoveEldestEntry. By overriding this method, you can tell Java to remove the oldest entry whenever a new one is added and the map exceeds a certain size.import java.util.LinkedHashMap; import java.util.Map; public class SimpleLRUCache<K, V> extends LinkedHashMap<K, V> { private final int capacity; public SimpleLRUCache(int capacity) { // true enables access-order; false enables insertion-order super(capacity, 0.75f, true); this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > capacity; } } - Implement Using Custom Doubly Linked List (The Manual Way):
If you cannot extend
LinkedHashMapor need to implement the logic from scratch for a technical interview or specific architectural requirement, follow these sub-steps:- Create a Node Class: Define a private inner class
Nodethat contains the key, the value, and pointers to theprevandnextnodes. - Initialize the Map and Boundary Nodes: Create a
HashMap<K, Node>to store the keys and their corresponding nodes. Initialize two dummy nodes,headandtail, to avoid null checks during node movement. - Implement the
addToHeadMethod: Write a helper function to insert a node immediately after theheaddummy node. This marks the item as the most recently used. - Implement the
removeNodeMethod: Write a helper function to detach a node from its current neighbors by updating their pointers. - Implement the
getMethod: Check if the key exists in the map. If it does, useremoveNodeand thenaddToHeadto move the accessed item to the front of the list. Return the value. - Implement the
putMethod: If the key already exists, update the value and move the node to the head. If it is a new key, create a new node and add it to the head. If the size now exceeds the capacity, remove the node immediately before thetaildummy node and delete its entry from the map.
- Create a Node Class: Define a private inner class
- Test the Implementation: Create a main method to instantiate your cache with a small capacity (e.g., 3). Add four different items and verify that the first item added is evicted. Access one of the older items and verify that it is no longer the first candidate for eviction.
Common Mistakes
- Forgetting Access Order: When using
LinkedHashMap, failing to passtrueto theaccessOrderparameter in the constructor. By default,LinkedHashMapuses insertion order, which creates a First-In-First-Out (FIFO) queue rather than an LRU cache. - Null Pointer Exceptions in Custom Lists: Failing to use dummy head and tail nodes. Managing the edges of a doubly linked list manually often leads to
NullPointerExceptionwhen the list is empty or contains only one element. - Ignoring Thread Safety: Standard
HashMapandLinkedHashMapare not thread-safe. If multiple threads access the cache, you may encounterConcurrentModificationExceptionor data corruption. - Memory Leaks: Not removing the key from the map when the node is evicted from the linked list, causing the map to grow indefinitely.
Tips
- Use Collections.synchronizedMap: To make a
LinkedHashMapimplementation thread-safe, wrap it usingCollections.synchronizedMap(new SimpleLRUCache(capacity)). - Generics: Always use generics (
<K, V>) to ensure type safety and avoid manual casting when retrieving values from the cache. - Complexity Analysis: Ensure your implementation maintains O(1) time complexity for both
getandputoperations. If you find yourself looping through the list to find an item, your implementation is incorrect.
Troubleshooting
- Cache not evicting: If using
LinkedHashMap, double-check thatremoveEldestEntryreturnstrueonly whensize() > capacity. If it always returnsfalse, the cache will grow without limit. - Wrong items being evicted: Verify the
accessOrderflag. If the cache is behaving like a FIFO queue, you likely left the flag asfalse. - Performance degradation: If the cache is slow, check for synchronization bottlenecks. If using a synchronized wrapper, consider using a
ConcurrentHashMapcombined with aConcurrentLinkedQueuefor very high-throughput systems, though this requires a more complex custom implementation.
Frequently Asked Questions
What is the time complexity of an LRU cache?
A properly implemented LRU cache has O(1) time complexity for both the get and put operations, as the map provides instant lookup and the doubly linked list provides instant updates to the order.
Why use a doubly linked list instead of a singly linked list?
A doubly linked list allows you to remove a node in O(1) time because you have immediate access to both the previous and next nodes. In a singly linked list, you would have to traverse from the head to find the previous node, resulting in O(n) time.
Can I use a PriorityQueue for LRU?
No, a PriorityQueue would result in O(log n) time for insertions and removals, which is less efficient than the O(1) offered by the Map/Linked-List combination.
Is LinkedHashMap always the best choice?
For most standard applications, yes. It is concise and well-tested. However, for high-concurrency environments, you may need a custom implementation using ConcurrentHashMap or a third-party library like Caffeine or Guava Cache.
What happens if the capacity is set to zero or negative?
Depending on the implementation, this could lead to an IllegalArgumentException or a cache that evicts every item immediately upon insertion. Always validate that capacity is greater than zero during initialization.