7

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!

Saurabh Gokhale
  • 53,625
  • 36
  • 139
  • 164
  • 3
    "In short, what it is that makes CHM not to throw ConcurrentModificationException, unlike HashMap?" Its implementation; it was designed to be used concurrently. Take a look at [the implementation](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/ConcurrentHashMap.java) if you're curious. – David Ehrmann Apr 03 '14 at 04:32

1 Answers1

14

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
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    So, the iterators will always contain only those values which were present during creation of iterator. They won't contain or even add/remove the value i.e "TQR" to the original map". If so, will the entry be added to some clone form of CHM ? – Saurabh Gokhale Apr 03 '14 at 04:36
  • u mean the iterator is iterating over the older (un-updated) object? – Arun Raaj Feb 24 '19 at 20:38
  • This works fine but when I remove 2nd or other entries, Iterator also remove that entries: Why so, I asked the same here: https://stackoverflow.com/questions/61440727/why-removing-1st-entry-from-map-does-not-reflect-but-removing-2nd-or-proceeding – Akhilesh Dhar Dubey Apr 26 '20 at 12:47