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

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

import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;

public class TestConcurrency {
    private static class Test1 implements Runnable {
        private RMap<String,Integer> cache;
        public Test1(RMap<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 Test2 implements Runnable {
        private RMap<String,Integer> cache;
        private Lock lck;
        public Test2(RMap<String,Integer> cache, Lock lck) {
            this.cache = cache;
            this.lck = lck;
        }
        @Override
        public void run() { 
            lck.lock();
            int hot = cache.get("hot");
            hot = hot + 1;
            cache.put("hot", hot);
            lck.unlock();
        }
    }
    private static class Test3 implements Runnable {
        private RMap<String,Integer> cache;
        public Test3(RMap<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 RAtomicLong counter;
        public Test4(RAtomicLong counter) {
            this.counter = counter;
        }
        @Override
        public void run() {
            counter.addAndGet(1);
        }
    }
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(RMap<String,Integer> cache, String lbl, Runnable action, RAtomicLong counter) 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);
        if(counter != null) {
            cache.put("hot",  (int)counter.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 {
        ((Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME)).setLevel(Level.WARN); // hack to avoid debug & info output
        Config cfg = new Config();
        //cfg.useClusterServers().addNodeAddress("redis://localhost:6379");
        cfg.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient client = Redisson.create(cfg);
        RMap<String,Integer> cache = client.getMap("concurrency_cache");
        Lock lck = client.getFairLock("hot");
        RAtomicLong counter = client.getAtomicLong("superhot");
        counter.set(0);
        test(cache, "No handling", new Test1(cache), null);
        test(cache, "Locking", new Test2(cache, lck), null);
        test(cache, "Replace with check", new Test3(cache), null);
        test(cache, "Atomic increment", new Test4(counter), counter);
        client.shutdown();    }
}
