Skip to content

Instantly share code, notes, and snippets.

@samueleresca
Last active April 29, 2020 17:34
Show Gist options
  • Save samueleresca/77d618fca0f6e5466455916386af81ed to your computer and use it in GitHub Desktop.
Save samueleresca/77d618fca0f6e5466455916386af81ed to your computer and use it in GitHub Desktop.
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