Last active
April 29, 2020 17:34
-
-
Save samueleresca/77d618fca0f6e5466455916386af81ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 _rw = new ReaderWriterLockSlim(); | |
private readonly int _capacity; | |
public LRUCacheReaderWriterLock(int capacity) | |
{ | |
_capacity = capacity; | |
} | |
public int Capacity => _capacity; | |
public object Get(int key) | |
{ | |
try | |
{ | |
_rw.EnterUpgradeableReadLock(); | |
var keyNotExists = !_records.ContainsKey(key); | |
if (keyNotExists) return null; | |
_rw.EnterWriteLock(); | |
_freq.Remove(key); | |
_freq.AddLast(key); | |
_rw.ExitWriteLock(); | |
return _records[key].CacheValue; | |
} | |
finally | |
{ | |
_rw.ExitUpgradeableReadLock(); | |
} | |
} | |
public void Set(int key, T val) | |
{ | |
... | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment