Least Recently Used (LRU) Algorithm in Java

In computer science, the Least Recently Used (LRU) algorithm is a caching strategy that discards the least recently used items first. This algorithm is commonly used in cache management to optimize performance by keeping frequently accessed data in memory.

How LRU Algorithm Works

The LRU algorithm maintains a queue of items with each item being accessed moving to the front of the queue. When the cache is full and a new item needs to be added, the least recently used item at the end of the queue is removed to make space for the new item.

LRU Algorithm can be implemented using a combination of a hashmap and a linked list. When an item is accessed, it is moved to the head of the linked list to show that it is the most recently used item. When the cache is full, the item at the end of the linked list (least recently used) is removed.

Example Implementation in Java

import java.util.LinkedHashMap;
import java.util.Map;

public class LRUCache<K, V> extends LinkedHashMap<K, V> {

    private int capacity;

    public LRUCache(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > capacity;
    }

    public static void main(String[] args) {
        LRUCache<Integer, String> cache = new LRUCache<>(3);
        cache.put(1, "One");
        cache.put(2, "Two");
        cache.put(3, "Three");

        System.out.println(cache);

        cache.get(1);
        System.out.println(cache);

        cache.put(4, "Four");
        System.out.println(cache);
    }
}

In this example, we have created an LRUCache class that extends LinkedHashMap to leverage its implementation. The constructor takes the capacity of the cache as a parameter. The removeEldestEntry method is overridden to remove the eldest entry when the cache exceeds its capacity.

Class Diagram

classDiagram
    LRUCache <|-- LinkedHashMap
    LRUCache : - capacity: int
    LRUCache : + LRUCache(capacity: int)
    LRUCache : + removeEldestEntry(eldest: Entry<K,V>): boolean
    LRUCache : + main(args: String[]): void

Conclusion

The Least Recently Used (LRU) algorithm is a popular caching strategy used to improve performance by keeping frequently accessed items in memory. By implementing the LRU algorithm in Java, we can efficiently manage cache and optimize memory usage in our applications.