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

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

import jakarta.nosql.Settings;
import jakarta.nosql.keyvalue.BucketManager;
import jakarta.nosql.keyvalue.BucketManagerFactory;
import jakarta.nosql.keyvalue.KeyValueConfiguration;

import org.eclipse.jnosql.diana.memcached.keyvalue.MemcachedKeyValueConfiguration;

public class TestConcurrency {
    private static class Test1 implements Runnable {
        private BucketManager cache;
        public Test1(BucketManager cache) {
            this.cache = cache;
        }
        @Override
        public void run() {
            int hot = (Integer)cache.get("hot").get().get();
            hot = hot + 1;
            cache.put("hot", hot);
        }
    }
   private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(BucketManager 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 = (Integer)cache.get("hot").get().get();
        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 {
        KeyValueConfiguration cfg = new MemcachedKeyValueConfiguration();
        Map<String, Object> props = new HashMap<>();
        props.put("memcached.host", "localhost:11211"); // necessary
        BucketManagerFactory bmf = cfg.get(Settings.of(props));
        BucketManager cache = bmf.getBucketManager("functional_cache"); // Map not supported
        test(cache, "No handling", new Test1(cache));
        bmf.close();
    }
}
