ConcurrentHashMap



Direct implements following Interfaces
Serializable
ConcurrentMap<K,V>
Map<K,V>

It has five constructors
ConcurrentHashMap()
it create an Empty map with a default InitialCapacity of 16, and LoadFactor (0.75) and concurrencyLevel (16).

ConcurrentHashMap(int initialCapacity)
it create an Empty map with the specified initial capacity, and with default LoadFactor (0.75) and concurrencyLevel (16).

ConcurrentHashMap(int initialCapacity, float loadFactor)
it create an Empty map with the specified initialCapacity and loadFactor and with the default concurrencyLevel (16).

ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel)
it create an Empty map with the specified initialCapacity, loadFactor and concurrencyLevel.

ConcurrentHashMap(Map<? extends K,? extends V> m)
It creates a new map with the mappings as the given map in the argument.

Points to Remember
It is available since java 1.5.
It is available in java.util.concurrent package.
It provides bucket level locking.
Get operation generally do not lock.
It add new entry at the beginning of the chain at any respective bucket.
Locks are used by mutative operations (put() and remove()).

Retrieval operation
Retrieval operation proceed by first finding the head pointer for the desired bucket (which is done without locking, so it could be stale), and traversing the bucket chain without acquiring the lock for that bucket. If it doesn't find the value it is looking for, it synchronizes and tries to find the entry again.

Removal operation
  • Removal is a two step process.
  • First it will find the approriate entry in the chain then it will set its value part as null.
  • Then it make a copy of the chain from the beginning of the chain to the removed element.
  • and join the chain with the trailing chain of the removed element.
  • If any thread is looking for the removed element then it will get null and it will
  • try to get the element again with synchronization.
  • Eventually, the initial part of the chain ending with the removed element will be garbage collected. 
  • remove() and put() holds the bucket lock for the duration of its execution.
  • put() searches the appropriate hash chain for the requested key. 
  • If it is found, then the value field (which is volatile) for that entry is simply updated. 
  • If it is not found, a new Entry object is created at the head of the list for that bucket.
  • Iterator returned by the concurrentHashMap is not fail-fast but it is weakly consistent.
  • It has avoided the inconsistency by making the Entry elements immutable.
  • All fields in Entry are final, except value field, It is volatile. 
  • This means that elements cannot be added to or removed from the middle or end of the hash chain.
  • Elements can only be added at the beginning, and remove operation involves to clone all or part of the chain and update the list head
  • pointer.