I recently did an example where I added the element to ConcurrentHashMap
while iterating over it.
Code snippet -
Map<String, String> map = new ConcurrentHashMap<String, String>();
map.put("ABC", "abc");
map.put("XYZ", "xyz");
map.put("MNO", "mno");
map.put("DEF", "def");
map.put("PQR", "pqr");
Iterator<Map.Entry<String, String>> entrySet = map.entrySet().iterator();
while(entrySet.hasNext()) {
Map.Entry<String, String> entry = entrySet.next();
System.out.println(entry.getKey()+", "+entry.getValue());
map.put("TQR", "tqr");
}
But I'm unable to find the exact reason as to why the code doesn't throw a ConcurrentModificationException in case of CHM.
In short, what it is that makes CHM not to throw ConcurrentModificationException, unlike HashMap.
Thank you!
ConcurrentHashMap API states that its iterators do not throw ConcurrentModificationException. This is because its iterators reflect the state of the hash table at point of the creation of the iterator. This is as if its iterators work with a hash table snapshot:
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(1, 1);
Iterator i = m.entrySet().iterator();
m.remove(1); // remove entry from map
System.out.println(i.next()); //still shows entry 1=1