Q. What output is expected from the following code? What does it actually output?
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
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)); } } } |
A. It is expected to output counts from 100,001 to 100,010, but actually the output will be as shown below missing counts. Output with missing counts
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Key-1 = 570087 Key-2 = 527793 Key-3 = 518048 Key-4 = 493989 Key-5 = 466364 Key-6 = 578612 Key-7 = 508259 Key-8 = 517953 Key-9 = 480131 Key-10 = 433976 Processed in 1777 ms |
Why does the output miss counts?… Read more...