Skip to content

Instantly share code, notes, and snippets.

@JeffreyZhao
Created November 15, 2009 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JeffreyZhao/235216 to your computer and use it in GitHub Desktop.
Save JeffreyZhao/235216 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.FSharp.Collections;
using System.Threading;
using System.Collections.Concurrent;
namespace CacheBenchmark
{
public interface IConcurrentCache<TKey, TValue>
{
TValue Get(TKey key);
void Set(TKey key, TValue value);
}
public class ImmutableMapCache<TKey, TValue> : IConcurrentCache<TKey, TValue>
{
private object m_writeLock = new object();
private FSharpMap<TKey, TValue> m_map = FSharpMap<TKey, TValue>.Empty;
public TValue Get(TKey key)
{
return this.m_map[key];
}
public void Set(TKey key, TValue value)
{
lock (this.m_writeLock)
{
this.m_map = this.m_map.Add(key, value);
}
}
}
public class ImmutableDictionaryCache<TKey, TValue> : IConcurrentCache<TKey, TValue>
{
private object m_writeLock = new object();
private Dictionary<TKey, TValue> m_dict = new Dictionary<TKey, TValue>();
public TValue Get(TKey key)
{
return this.m_dict[key];
}
public void Set(TKey key, TValue value)
{
lock (this.m_writeLock)
{
var newDict = this.m_dict.ToDictionary(p => p.Key, p => p.Value);
newDict[key] = value;
this.m_dict = newDict;
}
}
}
public class RwLockDictionaryCache<TKey, TValue> : IConcurrentCache<TKey, TValue>
{
private ReaderWriterLock m_rwLock = new ReaderWriterLock();
private Dictionary<TKey, TValue> m_dict = new Dictionary<TKey, TValue>();
public TValue Get(TKey key)
{
this.m_rwLock.AcquireReaderLock(0);
try
{
return this.m_dict[key];
}
finally
{
this.m_rwLock.ReleaseReaderLock();
}
}
public void Set(TKey key, TValue value)
{
this.m_rwLock.AcquireWriterLock(0);
try
{
this.m_dict[key] = value;
}
finally
{
this.m_rwLock.ReleaseWriterLock();
}
}
}
public class ConcurrentDictionaryCache<TKey, TValue> : IConcurrentCache<TKey, TValue>
{
private ConcurrentDictionary<TKey, TValue> m_dict = new ConcurrentDictionary<TKey, TValue>();
public TValue Get(TKey key)
{
return this.m_dict[key];
}
public void Set(TKey key, TValue value)
{
this.m_dict[key] = value;
}
}
public class RwLockSlimDictionaryCache<TKey, TValue> : IConcurrentCache<TKey, TValue>
{
private ReaderWriterLockSlim m_rwLock = new ReaderWriterLockSlim();
private Dictionary<TKey, TValue> m_dict = new Dictionary<TKey, TValue>();
public TValue Get(TKey key)
{
this.m_rwLock.EnterReadLock();
try
{
return this.m_dict[key];
}
finally
{
this.m_rwLock.ExitReadLock();
}
}
public void Set(TKey key, TValue value)
{
this.m_rwLock.EnterWriteLock();
try
{
this.m_dict[key] = value;
}
finally
{
this.m_rwLock.ExitWriteLock();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment