Saturday 18 April 2015

The ConcurrentHashMap is very similar to the java.util.HashTable class, except that ConcurrentHashMap offers better concurrency than HashTable does. ConcurrentHashMap does not lock the complete Map while you are reading from it. The ConcurrentHashMap enhances a Map by adding the atomic putIfAbsent, remove and replace methods. For example the putIfAbsent method is equivalent to performing the following code as an atomic operation. 

if(!map.containsKey(key))

   return map.put(key,value);
else
   return map.get(key);


Note that an Iterator of ConcurrentHashMap is weakly consistent, it can return elements from the point in time the Iterator was created or later. This means that while you are looping through a ConcurrentHashMap collection, you might observe elements that are being inserted by other threads. Moreover you may observe only some of the elements that are inserted by other threads. Similarly size method may produce inaccurate results. For example while you are counting the people in line, some people may join the line and others may leave. Your count might end up close but not exact by the time you reach end. This is the type of behavior you might see with a weekly consistent collection. 

The benefit to this type of behavior is that it is permissible for multiple threads to concurrently read and write a collection without having to create multiple internal copies of the collection as is the case on copy-on-write collection.a

Signature :

public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable


Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

Click HERE to know how segmentation is done in Concurrent Hashmap.