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!
How do you fix Java's ConcurrentModificationException? There are two basic approaches: Do not make any changes to a collection while an Iterator loops through it. If you can't stop the underlying collection from being modified during iteration, create a clone of the target data structure and iterate through the clone.
The ConcurrentModificationException generally occurs when working with Java Collections. The Collection classes in Java are very fail-fast and if they are attempted to be modified while a thread is iterating over it, a ConcurrentModificationException is thrown.
The ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible. This exception usually comes when one is working with Java Collection classes. For Example - It is not permissible for a thread to modify a Collection when some other thread is iterating over it.
Notice that iterator. remove() doesn't throw an exception by itself because it is able to update both the internal state of itself and the collection. Calling remove() on two iterators of the same instance collection would throw, however, because it would leave one of the iterators in an inconsistent state.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With