import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentHashMapTest {
public static void main(String[] args) {
Map<String, String> hMap = new HashMap<String, String>();
hMap.put("FIRST", "1");
hMap.put("SECOND", "2");
hMap.put("THIRD", "3");
hMap.put("FOURTH", "4");
hMap.put("FIFTH", "5");
hMap.put("SIXTH", "6");
System.out.println("HashMap before iteration : " + hMap);
Iterator<String> hashMapIterator = hMap.keySet().iterator();
while (hashMapIterator.hasNext()) {
String key = hashMapIterator.next();
if (key.equals("FOURTH")){
hMap.put(key + "-SHIVAM", "I AM NEW KEY IN HMAP");
}
}
System.out.println("HashMap after iteration : " + hMap);
}
}
Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(Unknown Source) at java.util.HashMap$KeyIterator.next(Unknown Source) at ConcurrentHashMapTest.main(ConcurrentHashMapTest.java:21)
I am wondering why this exception is coming. The exception is not at all seems to be fair in this case.