// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Threading; using Hazelcast.Core; using Hazelcast.Client; namespace Cache.Hazelcast.Concurrency { public class Program { private delegate void F(IMap cache); private static void Test1(IMap cache) { int? hot = cache.Get("hot"); hot = hot + 1; cache.Put("hot", hot); } private static void Test2(IMap cache, ILock lck) { lck.Lock(); int? hot = cache.Get("hot"); hot = hot + 1; cache.Put("hot", hot); lck.Unlock(); } private static void Test3(IMap cache) { bool done = false; while(!done) { int? hot1 = cache.Get("hot"); int? hot2 = hot1 + 1; done = cache.Replace("hot", hot1, hot2); } } private static void Test4(IAtomicLong counter) { counter.AddAndGet(1); } private static void Testn(IMap cache, int nrep, F action) { for(int i = 0; i < nrep; i++) { action(cache); } } private const int NTHREADS = 100; private const int NOPS = 10000; private static void Test(IMap cache, string lbl, F action, IAtomicLong counter) { DateTime dt1 = DateTime.Now; cache.Put("hot", 0); Thread[] t = new Thread[NTHREADS]; for(int i = 0; i < NTHREADS; i++) { t[i] = new Thread(() => Testn(cache, NOPS/NTHREADS, action)); } for(int i = 0; i < NTHREADS; i++) { t[i].Start(); } for(int i = 0; i < NTHREADS; i++) { t[i].Join(); } if(counter != null) { cache.Put("hot", (int)counter.Get()); } int? hot = cache.Get("hot"); DateTime dt2 = DateTime.Now; Console.WriteLine("{0} : {1} = {2} ({3} ms)", lbl, hot, NOPS, (int)((dt2 - dt1).TotalMilliseconds)); } public static void Main(string[] args) { IHazelcastInstance cli = HazelcastClient.NewHazelcastClient(); IMap cache = cli.GetMap("concurrency_cache"); ILock lck = cli.GetLock("hot"); IAtomicLong counter = cli.GetAtomicLong("superhot"); counter.Set(0); Test(cache, "No handling", c => Test1(c), null); Test(cache, "Locking", c => Test2(c, lck), null); Test(cache, "Replace with check", c => Test3(c), null); Test(cache, "Atomic increment", c => Test4(counter), counter); cli.Shutdown(); } } }