Skip to content

Instantly share code, notes, and snippets.

View samueleresca's full-sized avatar

Samuele Resca samueleresca

View GitHub Profile
public class LRUCacheSemaphore<T>
{
...
public object Get(int key)
{
_sem.Wait();
if (!_records.ContainsKey(key)) return null;
_freq.Remove(key);
using System.Collections.Generic;
using System.Threading;
namespace Blog.LRUCacheThreadSafe
{
public class LRUCacheSemaphore<T>
{
private readonly Dictionary<int, LRUCacheItem<T>> _records = new Dictionary<int, LRUCacheItem<T>>();
private readonly LinkedList<int> _freq = new LinkedList<int>();
private readonly SemaphoreSlim _sem = new SemaphoreSlim(1);
using System.Collections.Generic;
namespace Blog.LRUCacheThreadSafe
{
public class LRUCacheLock<T>
{
private readonly Dictionary<int, LRUCacheItem<T>> _records = new Dictionary<int, LRUCacheItem<T>>();
private readonly LinkedList<int> _freq = new LinkedList<int>();
private readonly int _capacity;
private static readonly object _locker = new object();
[Fact]
public async Task multiple_threads_should_get_data_correctly()
{
LRUCache<int> cache = new LRUCache<int>(3);
Task[] tasks = new[] {
Task.Run(() => cache.Set(1, 3)),
Task.Run(() => cache.Set(1, 3)),
Task.Run(() => cache.Set(1, 3))
};
using Xunit;
using Xunit.Abstractions;
namespace Blog.LRUCacheThreadSafe.Tests
{
public class LRUCacheTests
{
[Fact]
public void should_remove_least_accessed_records_when_capacity_is_reached()
using System.Collections.Generic;
namespace Blog.LRUCacheThreadSafe
{
public class LRUCache<T>
{
private readonly Dictionary<int, LRUCacheItem<T>> _records = new Dictionary<int, LRUCacheItem<T>>();
private readonly LinkedList<int> _freq = new LinkedList<int>();
private readonly int _capacity;
public class ThreadUnsafeClass
{
public OtherClass MyObject;
public void ThreadUnsafeClass()
{
MyObject = new OtherClass();
MyObject.InitializeDependencies();
}
public void Initializer() {
OtherClass localObj = new OtherClass();
localObj.InitializeDependencies();
Handler(localObj);
}
public void Handler(OtherClass localObj) {
localObj.Execute("value");
}
public void IncrementCounter() {
int counter = 0;
counter++;
}
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Blog.NotesOnThreading
{
class Program
{
static void Main(string[] args)
{