Q. What is wrong with the following code snippet?
|
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 |
import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class WhatIsWrong implements Runnable { //shared by threads final static Map<String, String> map = new HashMap<String, String>(); public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(100); for (int i = 0; i < 100; i++) { WhatIsWrong wiw = new WhatIsWrong(); pool.submit(wiw); } pool.shutdown(); pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS); } @Override public void run() { for (int i = 0; i < 1000000; i++) { map.put(Thread.currentThread().getName(), "wow-" + i); Object retrieved = map.get(Thread.currentThread().getName()); if(retrieved == null) { System.out.println("Race conmdition detected!!! Map is in inconsistent state"); } } } } |
A. It is NOT thread-safe as a “HashMap” is not thread-safe as per the Java API, and race conditions can leave the “map” in “inconsistent state”. It is very hard…