// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package cache.ignitesql;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.ignite.Ignition;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.client.ClientCache;
import org.apache.ignite.client.ClientCacheConfiguration;
import org.apache.ignite.client.IgniteClient;
import org.apache.ignite.configuration.ClientConfiguration;

public class TestConcurrency {
    private static Integer get(ClientCache<String,Integer> cache, String key) {
        List<List<?>> res = cache.query(new SqlFieldsQuery("SELECT cvalue FROM concurrency_cache WHERE ckey = ?").setSchema("PUBLIC").setArgs(key)).getAll();
        if(res.size() > 0) {
            return (Integer)res.get(0).get(0);
        } else {
            return null;
        }
    }
    private static void put(ClientCache<String,Integer> cache, String key, Integer value) {
        cache.query(new SqlFieldsQuery("MERGE INTO concurrency_cache(ckey,cvalue) VALUES(?,?)").setSchema("PUBLIC").setArgs(key, value)).getAll();
    }
    private static void add(ClientCache<String,Integer> cache, String key, Integer delta) {
        cache.query(new SqlFieldsQuery("UPDATE concurrency_cache SET cvalue = cvalue + ? WHERE ckey = ?").setSchema("PUBLIC").setArgs(delta, key)).getAll();
    }
    private static class Test1 implements Runnable {
        private ClientCache<String,Integer> cache;
        public Test1(ClientCache<String,Integer> cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            int hot = get(cache, "hot");
            hot = hot + 1;
            put(cache, "hot", hot);
        }
    }
    private static class Test6 implements Runnable {
        private ClientCache<String,Integer>cache;
        public Test6(ClientCache<String,Integer> cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            boolean done = false;
            while(!done) {
                try {
                    add(cache, "hot", 1);
                    done = true;
                } catch (Exception e) {
                    // retry
                }
            }
        }
    }
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(ClientCache<String,Integer> cache, String lbl, Runnable action) throws InterruptedException {
        long t1 = System.currentTimeMillis();
        put(cache, "hot", 0);
        ExecutorService es = Executors.newFixedThreadPool(NTHREADS);
        for(int i = 0; i < NOPS; i++) {
            es.submit(action);
        }
        es.shutdown();
        es.awaitTermination(300, TimeUnit.SECONDS);
        int hot = get(cache, "hot");
        long t2 = System.currentTimeMillis();
        System.out.printf("%s : %d = %d (%d ms)\n", lbl, hot, NOPS, t2 - t1);
    }
    public static void main(String[] args) throws Exception {
        ClientConfiguration cfg = new ClientConfiguration().setAddresses("localhost:10800");
        IgniteClient cli = Ignition.startClient(cfg);
        ClientCache<String,Integer> cache = cli.getOrCreateCache(new ClientCacheConfiguration().setName("dummy"));
        cache.query(new SqlFieldsQuery("CREATE TABLE IF NOT EXISTS concurrency_cache (ckey VARCHAR(16) NOT NULL, cvalue INTEGER NOT NULL, PRIMARY KEY(ckey))").setSchema("PUBLIC")).getAll();
        test(cache, "No handling", new Test1(cache));
        // transaction with retry  not available
        test(cache, "Update with retry", new Test6(cache));
        cli.close();
    }
}
