An open API service indexing awesome lists of open source software.

https://github.com/gireeshbharmshetty/java-lru-cache

A simple LRU (Least Recently Used) Cache implementation in Java using HashMap and Doubly Linked List.
https://github.com/gireeshbharmshetty/java-lru-cache

algorithms cache data-structures java lru-cache system-design

Last synced: 11 months ago
JSON representation

A simple LRU (Least Recently Used) Cache implementation in Java using HashMap and Doubly Linked List.

Awesome Lists containing this project

README

          

# Java LRU Cache Implementation

## Project Overview

This project provides a simple implementation of a Least Recently Used (LRU) cache in Java. An LRU cache is a fixed-size cache that automatically evicts the least recently used item when it needs to make space for a new item.

## How it Works

This implementation uses a combination of two data structures:

1. **`HashMap`:** Provides O(1) average time complexity for `get` and `put` operations by storing the key and a reference to the corresponding node in the linked list.
2. **Doubly Linked List:** Maintains the order of usage. The most recently used item is kept at the head of the list, and the least recently used item is kept at the tail. When an item is accessed (`get`) or updated (`put`), it is moved to the head. When the cache is full and a new item is added, the item at the tail is removed.

Dummy `head` and `tail` nodes are used in the doubly linked list to simplify the logic for adding and removing nodes, avoiding null checks for boundary conditions.

## Benefits & Relevance

* **Understanding Cache Eviction:** Demonstrates a common cache eviction strategy used in many systems.
* **Data Structure Practice:** Provides practical application of HashMaps and Doubly Linked Lists.
* **Interview Relevance:** LRU Cache implementation is a classic question in software engineering interviews, especially for roles involving system design or backend development.
* **Concurrency (Note):** This specific implementation is **not** thread-safe. For concurrent environments, synchronization mechanisms (like `ConcurrentHashMap` and explicit locking) would be required.

## How to Use/Run

1. **Compile:** You can compile the Java files using a Java Development Kit (JDK):
```bash
javac src/main/java/com/gireesh/cache/*.java
```
2. **Run the Demo:** Execute the `LRUCacheDemo` class to see the cache in action:
```bash
java -cp src/main/java com.gireesh.cache.LRUCacheDemo
```
The demo will show items being added, accessed, and evicted based on the LRU policy.

## Files

* `src/main/java/com/gireesh/cache/CacheNode.java`: Represents a node in the doubly linked list.
* `src/main/java/com/gireesh/cache/LRUCache.java`: The main LRU Cache implementation class.
* `src/main/java/com/gireesh/cache/LRUCacheDemo.java`: A simple class to demonstrate the cache functionality.