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

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

import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;

public class TestConcurrency {
    private static class Test1 implements Runnable {
        private Cache<String,Integer> cache;
        public Test1(Cache<String,Integer> cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            int hot = cache.get("hot");
            hot = hot + 1;
            cache.put("hot", hot);
        }
    }
    private static class Test3 implements Runnable {
        private Cache<String,Integer> cache;
        public Test3(Cache<String,Integer> cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            boolean done = false;
            while(!done) {
                int hot1 = cache.get("hot");
                int hot2 = hot1 + 1;
                done = cache.replace("hot", hot1, hot2);
            }
        }
    }
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(Cache<String,Integer> cache, String lbl, Runnable action) throws InterruptedException {
        long t1 = System.currentTimeMillis();
        cache.put("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 = cache.get("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 {
        CachingProvider cp = Caching.getCachingProvider("org.infinispan.jcache.remote.JCachingProvider");
        CacheManager cm = cp.getCacheManager();
        Cache<String,Integer> cache = cm.getCache("concurrency_cache");
        if(cache == null) {
            cache = cm.createCache("concurrency_cache", new MutableConfiguration<String,Integer>());
        }
        test(cache, "No handling", new Test1(cache));
        test(cache, "Replace with check", new Test3(cache));
        cache.close();
        cm.close();
        cp.close();
    }
}
