Saturday, June 19, 2010

ConcurrentHashMap :Be Careful while Iterating over

As Per Java Docs Iterator for ConcurrenthashMap does not guarantee to reflect concurrent changes in the map. It is due to the way thread safety for add/remove/update operations has been internally implemented in ConcurrentHashMap- ConcurrentHashMap internally divides the complete map in structures known as Buckets which can be accessed/Locked independently.

So, in order to avoid any NullPointerExceptions being thrown we need have a check for nulls being returned before making any calls on returned object. See snippet below to understand it further :-

Iterator it = testConcHashMap.keySet().iterator();
while(it.hasNext()) {
String key= (String)it.next();
String value= testConcHashMap.get(key);
//value.equals("anotherstring");//May throw a Null Pointer

if(! (value== null)){ //check for null
value.equals("anotherstring");
}
}


For further reading see java docs : http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ConcurrentHashMap.html