Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 776
e2rabi Avatar asked Dec 03 '25 14:12

e2rabi


1 Answers

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); 
like image 198
Matt Timmermans Avatar answered Dec 05 '25 05:12

Matt Timmermans



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!