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

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

import net.spy.memcached.AddrUtil;
import net.spy.memcached.CASResponse;
import net.spy.memcached.CASValue;
import net.spy.memcached.ConnectionFactoryBuilder;
import net.spy.memcached.MemcachedClient;
import net.spy.memcached.ConnectionFactoryBuilder.Protocol;

public class TestConcurrency {
    private static class Test1 implements Runnable {
        private MemcachedClient cache;
        public Test1(MemcachedClient cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            int hot = (Integer)cache.get("hot");
            hot = hot + 1;
            cache.set("hot", 0, hot);
        }
    }
    private static class Test3 implements Runnable {
        private MemcachedClient cache;
        public Test3(MemcachedClient cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            while(true) {
                CASValue<Object> res = cache.gets("hot");
                int hot = (Integer)res.getValue();
                hot = hot + 1;
                if(cache.cas("hot", res.getCas(), hot) == CASResponse.OK) break;
            }
        }
    }
    ////private static class Test4 implements Runnable {
    ////    private MemcachedClient cache;
    ////    public Test4(MemcachedClient cache) {
    ////        this.cache = cache;
    ////    }
    ////    @Override
    ////    public void run() {
    ////        cache.incr("hot", 1);
    ////    }
    ////}
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(MemcachedClient cache, String lbl, Runnable action) throws InterruptedException {
        long t1 = System.currentTimeMillis();
        cache.set("hot", 0, 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 = (Integer)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 {
        MemcachedClient cache = new MemcachedClient(new ConnectionFactoryBuilder().setProtocol(Protocol.BINARY).build(), AddrUtil.getAddresses("localhost:11211"));
        test(cache, "No handling", new Test1(cache));
        test(cache, "Replace with check", new Test3(cache));
        // atomic increment does not work in 2.12.3
        ////test(cache, "Atomic increment", new Test4(cache));
        cache.shutdown();
    }
}
