Using ConcurrentHashMap
is recommended for large Maps or large number of read-write operations due to:
- When reading from the map, it's not locked. Thus, if 5 threads are reading from it, all of them can simultaneously read from map.
- On writing, only the relevant record (key) is locked. Thus, if 5 threads are writing values of different keys, all those operations can happen simultaneously. However, if 2 threads are writing to same key, those operations are thread-safe. That happens because there is no locking at the object (map) level but at a much finer granularity - at a hashmap bucket level.
Consider the following example:
public class ConcurrentHashMapExample {
public static void main(String[] args) {
//ConcurrentHashMap
Map<String,String> myMap = new ConcurrentHashMap<String,String>();
myMap.put("1", "1");
myMap.put("2", "1");
myMap.put("3", "1");
myMap.put("4", "1");
myMap.put("5", "1");
myMap.put("6", "1");
System.out.println("ConcurrentHashMap before iterator: "+myMap);
Iterator<String> itr1 = myMap.keySet().iterator();
while(itr1.hasNext()){
String key = itr1.next();
if(key.equals("3")) myMap.put(key+"new", "new3");
}
System.out.println("ConcurrentHashMap after iterator: "+myMap);
//HashMap
myMap = new HashMap<String,String>();
myMap.put("1", "1");
myMap.put("2", "1");
myMap.put("3", "1");
myMap.put("4", "1");
myMap.put("5", "1");
myMap.put("6", "1");
System.out.println("HashMap before iterator: "+myMap);
Iterator<String> itr2 = myMap.keySet().iterator();
while(itr2.hasNext()){
String key = itr2.next();
if(key.equals("3")) myMap.put(key+"new", "new3");
}
System.out.println("HashMap after iterator: "+myMap);
}
}
The output will be:
ConcurrentHashMap before iterator: {1=1, 5=1, 6=1, 3=1, 4=1, 2=1}
ConcurrentHashMap after iterator: {1=1, 3new=new3, 5=1, 6=1, 3=1, 4=1, 2=1}
HashMap before iterator: {3=1, 2=1, 1=1, 6=1, 5=1, 4=1}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at com.test.ConcurrentHashMapExample.main(ConcurrentHashMapExample.java:44)
As you can see, for the HashMap
a ConcurrentModificationException
will be thrown because you trying to change a map that you currently iterating on! (specifically, the exception will be thrown on the statement : String key = itr1.next();
)