import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public final class WhatIsWrong implements Runnable {
private Map<String, Integer> myMap = null;
public WhatIsWrong(Map<String, Integer> myMap) {
this.myMap = myMap;
}
public static void main(String[] args) throws InterruptedException {
long start = System.currentTimeMillis();
Map<String, Integer> myMap = Collections.synchronizedMap(new HashMap<String, Integer>());
for (int i = 1; i <= 10; i++) {
myMap.put("Key-" + i, i); // 10 items in the map
}
// process 1 million times with 20 threads
ExecutorService threadPool = Executors.newFixedThreadPool(20);
for (int i = 1; i <= 1000000; i++) {
WhatIsWrong wiw = new WhatIsWrong(myMap);
threadPool.submit(wiw); //submit 1 million tasks to the thread pool
}
threadPool.shutdown();
threadPool.awaitTermination(60, TimeUnit.SECONDS);
traverseAndPrint(myMap);
long finish = System.currentTimeMillis();
System.out.println("Processed in " + (finish - start) + " ms");
}
@Override
public void run() {
traverseAndUpdate();
}
private void traverseAndUpdate() {
Iterator<String> it = myMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Integer newValue = this.myMap.get(key) + 1;
myMap.put(key, newValue);
}
}
private static void traverseAndPrint(Map<String, Integer> myMap) {
Iterator<String> it = myMap.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key + " = " + myMap.get(key));
}
}
}