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

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

import org.infinispan.client.hotrod.DefaultTemplate;
import org.infinispan.client.hotrod.RemoteCache;
import org.infinispan.client.hotrod.RemoteCacheManager;
import org.infinispan.client.hotrod.RemoteCounterManagerFactory;
import org.infinispan.client.hotrod.configuration.ConfigurationBuilder;
import org.infinispan.client.hotrod.impl.ConfigurationProperties;
import org.infinispan.counter.api.CounterConfiguration;
import org.infinispan.counter.api.CounterManager;
import org.infinispan.counter.api.CounterType;
import org.infinispan.counter.api.StrongCounter;

public class TestConcurrency {
    private static class Test1 implements Runnable {
        private RemoteCache<String,Integer> cache;
        public Test1(RemoteCache<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 RemoteCache<String,Integer> cache;
        public Test3(RemoteCache<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 class Test4 implements Runnable {
        private StrongCounter counter;
        public Test4(StrongCounter counter) {
            this.counter = counter;
        }
        @Override
        public void run() {
            try {
                counter.addAndGet(1).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(RemoteCache<String,Integer> cache, String lbl, Runnable action, StrongCounter counter) throws InterruptedException, ExecutionException {
        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);
        if(counter != null) {
            cache.put("hot",  (int)(long)counter.getValue().get());
        }
        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 {
        ConfigurationBuilder b = new ConfigurationBuilder();
        b.addServer().host("localhost").port(ConfigurationProperties.DEFAULT_HOTROD_PORT);
        RemoteCacheManager rcm = new RemoteCacheManager(b.build());
        RemoteCache<String,Integer> cache = rcm.administration().getOrCreateCache("concurrency_cache", DefaultTemplate.DIST_SYNC);
        CounterManager cm = RemoteCounterManagerFactory.asCounterManager(rcm);
        cm.defineCounter("superhot", CounterConfiguration.builder(CounterType.UNBOUNDED_STRONG).initialValue(0).build());
        StrongCounter counter = cm.getStrongCounter("superhot");
        counter.reset().get();
        test(cache, "No handling", new Test1(cache), null);
        // Infinispan only supports locking for embedded cache - not for remote access to standalone cache server
        test(cache, "Replace with check", new Test3(cache), null);
        test(cache, "Atomic increment", new Test4(counter), counter);
        rcm.stop();
        rcm.close();
    }
}
