Advertisement
mahldcat

LRUCacheGeneric.cs

May 8th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1.  
  2. namespace Library;
  3.  
  4. public class LRUCache<K,V>
  5. {
  6. private object _syncRoot =new object();
  7.  
  8. private readonly Dictionary<K, LinkedListNode<KeyValuePair<K,V>>> _dictionary;
  9. private readonly LinkedList<KeyValuePair<K,V>> _linkedList;
  10. private readonly int _boundedCapacity;
  11.  
  12. public LRUCache(int boundedCapacity)
  13. {
  14.  
  15. if (boundedCapacity < 0)
  16. throw new ArgumentOutOfRangeException(nameof(boundedCapacity));
  17. _dictionary = new(boundedCapacity + 1);
  18. _linkedList = new();
  19. _boundedCapacity = boundedCapacity;
  20. }
  21.  
  22.  
  23. public int Count
  24. {
  25. get
  26. {
  27. lock (_syncRoot) return _dictionary.Count;
  28. }
  29. }
  30.  
  31. public V Get(K key)
  32. {
  33. V retVal = default(V);
  34. lock (_syncRoot)
  35. {
  36. if (_dictionary.TryGetValue(key, out var refNode))
  37. {
  38. retVal = refNode.Value.Value;
  39. if (!ReferenceEquals(refNode, _linkedList.Last))
  40. {
  41. _linkedList.Remove(refNode);
  42. _linkedList.AddLast(refNode);
  43. }
  44. }
  45. }
  46.  
  47. return retVal;
  48. }
  49.  
  50. public void Put(K key, V value)
  51. {
  52. lock (_syncRoot)
  53. {
  54. if (_dictionary.TryGetValue(key, out var refNode ))
  55. {
  56. refNode.Value = new KeyValuePair<K, V>(key, value);
  57. if (!ReferenceEquals(refNode, _linkedList.Last))
  58. {
  59. _linkedList.Remove(refNode);
  60. _linkedList.AddLast(refNode);
  61. }
  62. }
  63. else
  64. {
  65. refNode = new LinkedListNode<KeyValuePair<K,V>>(new KeyValuePair<K, V>(key, value));
  66. _linkedList.AddLast(refNode);
  67. _dictionary.Add(key,refNode);
  68. if (_dictionary.Count > _boundedCapacity)
  69. {
  70. _ = _dictionary.Remove(_linkedList.First!.Value.Key);
  71. _linkedList.RemoveFirst();
  72. }
  73. }
  74. }
  75. }
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement