Confused on the difference between ConcurrentHashMap and HashMap behavior in this example

e2rabi :

I'm trying to understand how ConcurrentHashMap works. I found an example, but I'm not able to understand it. Here's its code:

Map<String, Object> myData = new HashMap<String, Object>();
myData.put("A", 1);
myData.put("B", 2);
for (String key : myData.keySet()) {
    myData.remove(key);
}

This will throw an exception ConcurrentModificationException at runtime.

However, this code using ConcurrentHashMap will work correctly:

Map<String, Object> myData = new ConcurrentHashMap<String, Object>();
myData.put("A", 1);
myData.put("B", 2);
for (String key : myData.keySet()) }
    myData.remove(key);
}

Can someone explain to me why ConcurrentHashMap allows to remove keys while the HashMap throws an exception? Thanks

Matt Timmermans :

That's just one of the features of ConcurrentHashMap. To quote from the docs:

Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException.

ConcurrentHashMap does not really do this to support your use case, however. It's done to allow iteration in one thread happen concurrently with modifications made in other threads.

If this is your only reason for using ConcurrentHashMap, then you should probably reconsider, because it is a lot more expensive than HashMap. You are better off just making a copy of the key set before using it like this:

Map<String, Object> myData = new HashMap<String, Object>();
myData.put("A", 1);
myData.put("B", 2);
for(String key: myData.keySet().toArray(new String[0]))
    myData.remove(key); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=87675&siteId=1