Introduction
The LRUCache<TKey, TValue> class is a custom implementation of a Least Recently Used (LRU) cache. An LRU cache is a data structure that retains a fixed number of items and evicts the least recently used item when the cache exceeds its capacity. This is particularly useful for scenarios where memory usage needs to be constrained while still keeping frequently accessed data readily available.
The implementation provided offers thread safety ensures efficient eviction, and includes robust resource management. This article will analyze the class, its design decisions, thread safety mechanisms, and other noteworthy aspects.
Why Use an LRU Cache?
The main use case for an LRU cache is to optimize resource usage when dealing with limited memory. Examples include,
- Caching database query results: Only the most recent results are stored to avoid repeated expensive operations.
- Image or file caching: Reducing I/O or computation for commonly accessed resources.
- Web server session management: Limiting sessions stored in memory.
Key Features of This Implementation
- Fixed capacity: Enforces an upper limit on the cache size.
- Automatic eviction: Least recently used items are removed when capacity is exceeded.
- Thread safety: Ensures safe concurrent access in multi-threaded environments.
- Disposability: Proper cleanup of disposable items when evicted or when the cache is cleared.
Class Structure and Components
The LRUCache class is built using.
- ConcurrentDictionary<TKey, LinkedListNode<(TKey, TValue)>>
- Provides O(1) lookup for keys in the cache.
- Maps keys to their corresponding nodes in the LRU list.
- LinkedList<(TKey, TValue)>
- Maintains the ordering of items based on access (most recently used items at the front).
- Provides O(1) insertion and removal when moving nodes.
- Locking Mechanism: A private object _lock is used to synchronize access to the LinkedList and ensure thread safety during modifications.
Key Methods
Thread Safety and Locking
While the ConcurrentDictionary ensures thread-safe key lookups and modifications, the LinkedList requires explicit locking when accessed. This dual approach optimizes for the fast-path scenario (key lookup) while ensuring correctness for the slow-path scenario (adding, removing, or reordering nodes).
Example. Thread-Safe Access in Set.
lock (_lock)
{
if (_cacheMap.TryGetValue(key, out var existingNode))
{
_lruList.Remove(existingNode);
DisposeIfRequired(existingNode.Value.Value);
existingNode.Value = (key, value);
_lruList.AddFirst(existingNode);
}
else
{
var newNode = new LinkedListNode<(TKey Key, TValue Value)>((key, value));
_lruList.AddFirst(newNode);
_cacheMap[key] = newNode;
if (_cacheMap.Count > _capacity)
{
var lruNode = _lruList.Last;
if (lruNode != null)
{
_lruList.RemoveLast();
_cacheMap.TryRemove(lruNode.Value.Key, out _);
DisposeIfRequired(lruNode.Value.Value);
}
}
}
}

Join the conversation! Your thoughts help the community grow.