// 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 redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class TestConcurrency {
    private static final int CONCURRENCY_CACHE = 2;
    private static class Test1 implements Runnable {
        private JedisPool pool;
        public Test1(JedisPool pool) {
            this.pool = pool;
        }
        @Override
        public void run() { 
            Jedis cache = pool.getResource();
            cache.select(CONCURRENCY_CACHE);
            int hot = Integer.parseInt(cache.get("hot"));
            hot = hot + 1;
            cache.set("hot", Integer.toString(hot));
            cache.close();
        }
    }
    private static class Test4 implements Runnable {
        private JedisPool pool;
        public Test4(JedisPool pool) {
            this.pool = pool;
        }
        @Override
        public void run() {
            Jedis cache = pool.getResource();
            cache.select(CONCURRENCY_CACHE);
            cache.incrBy("hot",  1);
            cache.close();
        }
    }
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(JedisPool pool, String lbl, Runnable action) throws InterruptedException {
        Jedis cache = pool.getResource(); // Jedis object is not thread safe but JedisPool is
        cache.select(CONCURRENCY_CACHE);
        long t1 = System.currentTimeMillis();
        cache.set("hot", Integer.toString(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.parseInt(cache.get("hot"));
        long t2 = System.currentTimeMillis();
        System.out.printf("%s : %d = %d (%d ms)\n", lbl, hot, NOPS, t2 - t1);
        cache.close();
    }
    public static void main(String[] args) throws Exception {
        JedisPoolConfig cfg = new JedisPoolConfig();
        cfg.setMaxTotal(NTHREADS + 10);
        JedisPool pool = new JedisPool(cfg, "localhost", 6379);
        test(pool, "No handling", new Test1(pool));
        // replace with check did not work for me
        test(pool, "Atomic increment", new Test4(pool));
        pool.close();
    }
}
