// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;

public class MTMap {
    private static final int REP = 3;
    private static final int N = 10000000;
    public static void test(Map<String, String> m, int poolsiz) {
        ForkJoinPool pool = new ForkJoinPool(poolsiz);
        ForkJoinTask<?>[] tasks = new ForkJoinTask[poolsiz];
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < poolsiz; i++) {
            tasks[i] = pool.submit(new Adder(i * N / poolsiz, N / poolsiz, m));
        }
        for(int i = 0; i < poolsiz; i++) {
            tasks[i].join();
        }
        long t2 = System.currentTimeMillis();
        pool.shutdown();
        if(m.size() != N) {
            throw new RuntimeException("Wrong number of elements: " + m.size());
        }
        System.out.printf("%s : %d puts in %d threads = %d ms\n", m.getClass().getName(), N, poolsiz, t2 - t1);
    }
    public static void main(String[] args) {
        for(int i = 0; i < REP; i++) {
            test(new HashMap<String, String>(N), 1);
            test(new Hashtable<String, String>(N), 1);
            test(new ConcurrentHashMap<String, String>(N), 1);
            //test(new HashMap<String, String>(N), 2);
            test(new Hashtable<String, String>(N), 2);
            test(new ConcurrentHashMap<String, String>(N), 2);
            //test(new HashMap<String, String>(N), 10);
            test(new Hashtable<String, String>(N), 10);
            test(new ConcurrentHashMap<String, String>(N), 10);
            //test(new HashMap<String, String>(N), 100);
            test(new Hashtable<String, String>(N), 100);
            test(new ConcurrentHashMap<String, String>(N), 100);
        }
    }
}

class Adder implements Runnable {
    private int start;
    private int n;
    private Map<String, String> m;
    public Adder(int start, int n, Map<String, String> m) {
        super();
        this.start = start;
        this.n = n;
        this.m = m;
    }
    public void run() {
        for(int i = start; i < start + n; i++) {
            String key = "Key #" + i;
            String value = "Value #" + i;
            if(m.containsKey(key)) {
                throw new RuntimeException("Key already exists: " + key);   
            }
            if(m.get(key) != null) {
                throw new RuntimeException("Key already exists: " + key);   
            }
            m.put(key, value);
        }
    }
}
