// 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.Collections.Generic; using System.Threading; using Apache.Ignite.Core; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Cache.Query; namespace Cache.IgniteSql.Concurrency { public class Program { private static int? Get(ICacheClient cache, String key) { SqlFieldsQuery sfq = new SqlFieldsQuery("SELECT cvalue FROM concurrency_cache WHERE ckey = ?"); sfq.Schema = "PUBLIC"; sfq.Arguments = new object[] { key }; IList> res = cache.Query(sfq).GetAll(); if(res.Count > 0) { return (int?)res[0][0]; } else { return null; } } private static void Put(ICacheClient cache, String key, int? value) { SqlFieldsQuery sfq = new SqlFieldsQuery("MERGE INTO concurrency_cache(ckey,cvalue) VALUES(?,?)"); sfq.Schema = "PUBLIC"; sfq.Arguments = new object[] { key, value }; cache.Query(sfq).GetAll(); } private static void Add(ICacheClient cache, String key, int? delta) { SqlFieldsQuery sfq = new SqlFieldsQuery("UPDATE concurrency_cache SET cvalue = cvalue + ? WHERE ckey = ?"); sfq.Schema = "PUBLIC"; sfq.Arguments = new object[] { delta, key }; cache.Query(sfq).GetAll(); } private delegate void F(ICacheClient cache); private static void Test1(ICacheClient cache) { int? hot = Get(cache, "hot"); hot = hot + 1; Put(cache, "hot", hot); } private static void Test6(ICacheClient cache) { bool done = false; while(!done) { try { Add(cache, "hot", 1); done = true; } catch(Exception) { // retry } } } private static void Testn(ICacheClient 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(ICacheClient cache, string lbl, F action) { DateTime dt1 = DateTime.Now; Put(cache, "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(); } int? hot = Get(cache, "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) { IgniteClientConfiguration cfg = new IgniteClientConfiguration { Endpoints = new List { "localhost:10800" } }; using (IIgniteClient cli = Ignition.StartClient(cfg)) { ICacheClient cache = cli.GetOrCreateCache("concurrency_cache"); SqlFieldsQuery sfq = new SqlFieldsQuery("CREATE TABLE IF NOT EXISTS concurrency_cache (ckey VARCHAR(16) NOT NULL, cvalue INTEGER NOT NULL, PRIMARY KEY(ckey))"); sfq.Schema = "PUBLIC"; cache.Query(sfq).GetAll(); Test(cache, "No handling", c => Test1(c)); // transaction with retry not available Test(cache, "Update with retry", c => Test6(c)); } } } }