Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace Library;
- public class LRUCache<K,V>
- {
- private object _syncRoot =new object();
- private readonly Dictionary<K, LinkedListNode<KeyValuePair<K,V>>> _dictionary;
- private readonly LinkedList<KeyValuePair<K,V>> _linkedList;
- private readonly int _boundedCapacity;
- public LRUCache(int boundedCapacity)
- {
- if (boundedCapacity < 0)
- throw new ArgumentOutOfRangeException(nameof(boundedCapacity));
- _dictionary = new(boundedCapacity + 1);
- _linkedList = new();
- _boundedCapacity = boundedCapacity;
- }
- public int Count
- {
- get
- {
- lock (_syncRoot) return _dictionary.Count;
- }
- }
- public V Get(K key)
- {
- V retVal = default(V);
- lock (_syncRoot)
- {
- if (_dictionary.TryGetValue(key, out var refNode))
- {
- retVal = refNode.Value.Value;
- if (!ReferenceEquals(refNode, _linkedList.Last))
- {
- _linkedList.Remove(refNode);
- _linkedList.AddLast(refNode);
- }
- }
- }
- return retVal;
- }
- public void Put(K key, V value)
- {
- lock (_syncRoot)
- {
- if (_dictionary.TryGetValue(key, out var refNode ))
- {
- refNode.Value = new KeyValuePair<K, V>(key, value);
- if (!ReferenceEquals(refNode, _linkedList.Last))
- {
- _linkedList.Remove(refNode);
- _linkedList.AddLast(refNode);
- }
- }
- else
- {
- refNode = new LinkedListNode<KeyValuePair<K,V>>(new KeyValuePair<K, V>(key, value));
- _linkedList.AddLast(refNode);
- _dictionary.Add(key,refNode);
- if (_dictionary.Count > _boundedCapacity)
- {
- _ = _dictionary.Remove(_linkedList.First!.Value.Key);
- _linkedList.RemoveFirst();
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement