-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLRUCacheReaderWriterLock.cs
More file actions
73 lines (60 loc) · 2.02 KB
/
Copy pathLRUCacheReaderWriterLock.cs
File metadata and controls
73 lines (60 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
using System.Collections.Generic;
using System.Threading;
namespace Blog.LRUCacheThreadSafe
{
public class LRUCacheReaderWriterLock<T>
{
private readonly Dictionary<int, LRUCacheItem<T>> _records = new Dictionary<int, LRUCacheItem<T>>();
private readonly LinkedList<int> _freq = new LinkedList<int>();
private readonly ReaderWriterLockSlim _readerWriterLockSlim = new ReaderWriterLockSlim();
private readonly int _capacity;
public LRUCacheReaderWriterLock(int capacity)
{
_capacity = capacity;
}
public int Capacity => _capacity;
public object Get(int key)
{
try
{
_readerWriterLockSlim.EnterUpgradeableReadLock();
var keyNotExists = !_records.ContainsKey(key);
if (keyNotExists) return null;
_readerWriterLockSlim.EnterWriteLock();
_freq.Remove(key);
_freq.AddLast(key);
_readerWriterLockSlim.ExitWriteLock();
return _records[key].CacheValue;
}
finally
{
_readerWriterLockSlim.ExitUpgradeableReadLock();
}
}
public void Set(int key, T val)
{
try
{
_readerWriterLockSlim.EnterWriteLock();
if (_records.ContainsKey(key))
{
_records[key].CacheValue = val;
_freq.Remove(key);
_freq.AddLast(key);
return;
}
if (_records.Count >= _capacity)
{
_records.Remove(_freq.First.Value);
_freq.RemoveFirst();
}
_records.Add(key, new LRUCacheItem<T> { CacheKey = key, CacheValue = val });
_freq.AddLast(key);
}
finally
{
_readerWriterLockSlim.ExitWriteLock();
}
}
}
}