Reputation: 91949
I was reading the article "Java theory and practice: Building a better HashMap" that gives an excellent overview about the implementation of ConcurrentHashMap.
I also found some discussions over it on Stackoverflow here.
I question though I had in my mind is "what are the scenarios/applications/places" where ConcurrentHashMap is used.
Thank you
Upvotes: 6
Views: 7658
Reputation: 15413
Using ConcurrentHashMap
is recommended for large Maps or large number of read-write operations due to:
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();
)
Upvotes: 2
Reputation: 22415
You would use a ConcurrentHashMap
in the same instances you would use a HashMap
, except that you plan on more than one thread using the map.
Upvotes: 6
Reputation: 420991
I use it for quick lookup from user ids to user objects in a multi-threaded server for instance.
I have a network-thread, a timer thread for periodical tasks and a thread for handling console input. Multiple threads access the hash map of users, thus it needs to be thread safe.
Upvotes: 2