ConcurrentHashMap is very similar to HashTable but it provides better concurrency level.
You might know , you can synchonize HashTable using Collections.synchronizedMap(Map). So what is difference between ConcurrentHashMap and Collections.synchronizedMap(Map)

In case of Collections.synchronizedMap(Map), it locks whole HashTable object but in ConcurrentHashMap, it locks only part of it. You will understand it in later part.
Another difference is that ConcurrentHashMap will not throw ConcurrentModification exception if we try to modify ConcurrentHashMap while iterating it.

Lets take a very simple example. I have a Country class, we are going to use Country class object as key and its capital name(string) as value. Below example will help you to understand, how these key value pair will be stored in ConcurrentHashMap.

package org.arpit.java2blog;
public class Country {

 String name;
 long population;
 public Country(String name, long population) {
  super(); = name;
  this.population = population;
 public String getName() {
  return name;
 public void setName(String name) { = name;
 public long getPopulation() {
  return population;
 public void setPopulation(long population) {
  this.population = population;
public int hashCode() {
 final int prime = 31;
 int result = 1;
 result = prime * result + ((name == null) ? 0 : name.hashCode());
 return result;
 public boolean equals(Object obj) {
  Country other = (Country) obj;
   if (name.equalsIgnoreCase((
   return true;
  return false;

2. class)

import java.util.HashMap;
import java.util.Iterator;
public class ConcurrentHashMapStructure {
     * @author Arpit Mandliya
    public static void main(String[] args) {
        Country india=new Country("India",1000);
        Country japan=new Country("Japan",10000);
        Country france=new Country("France",2000);
        Country russia=new Country("Russia",20000);
        ConcurrentHashMap<country,String> countryCapitalMap=new ConcurrentHashMap<country,String>();
        Iterator<country> countryCapitalIter=countryCapitalMap.keySet().iterator();//put debug point at this line
            String capital=countryCapitalMap.get(countryObj);
Now put debug point at line 23 and right click on project->debug as-> java application. Program will stop execution at line 23 then right click on countryCapitalMap then select watch.You will be able to see structure as below.

Now From above diagram, you can observe following points
  1. There is an Segment[] array called segments which has size 16. 
  2. It has two more variable called segmentShift and segmentMask.
  3. This segments stores Segment class's object. ConcurrentHashMap class has a inner class called Segment
  4.  /**
         * Segments are specialized versions of hash tables.  This
         * subclasses from ReentrantLock opportunistically, just to
         * simplify some locking and avoid separate construction.
    static final class Segment<K,V> extends ReentrantLock implements Serializable {
          * The per-segment table.
            transient volatile HashEntry<K,V>[] table;
    // other methods and variables
Now lets expand segment object present at index 3.

In above diagram, you can see each Segment class contains logically an HashMap.
Here size of table[](Array of HashEntry class) : 2ˆk >= (capacity/number of segments)
It stores a key value pair in a class called HashEntry which is similar to Entry class in HashMap.

static final class HashEntry<K,V> {
        final K key;
        final int hash;
        volatile V value;
        final HashEntry<K,V> next;

When we say, ConcurrentHashMap locks only part of it.It actually locks a Segment. So  if two threads are  writing different segments in same ConcurrentHashMap, it allows write operation without any conflicts.

So Segments are only for write operations. In case of read operation, it allows full concurrency and provides most recently updated value using volatile variables.
Now as you understood internal structure of ConcurrentHashMap, it will be easier for you to understand put function.

Concept of ConcurrencyLevel:

While creating a ConcurrentHashMap object, you can pass ConcurrencyLevel in the constructor. ConcurrencyLevel defines"Estimated number of threads going to write to the ConcurrentHashMap". Default ConcurrencyLevel is 16. That is why, we got 16 Segments objects in above created ConcurrentHashMap.
Actual number of Segment will be equal to next power of two defined in ConcurrencyLevel.
For example:
Lets say you have defined ConcurrencyLevel as 5, so 8 Segments object will be created  as 8=2^3 so 3 higher bits of Key will be used to find index of the segment
Another example: You want 10 threads should be able to access ConcurrentHashMap concurrently, so you will define  ConcurrencyLevel as 10 , So 16 Segments will be created as 16=2^4 so 4 higher bits of Key will be used to find index of the segment

put Entry:

Code for putEntry is as follows:
     * Maps the specified key to the specified value in this table.
     * Neither the key nor the value can be null.
     * The value can be retrieved by calling the get method
     * with a key that is equal to the original key.
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with key, or
     *         null if there was no mapping for key
     * @throws NullPointerException if the specified key or value is null
    public V put(K key, V value) {
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).put(key, hash, value, false);

     * Returns the segment that should be used for key with given hash
     * @param hash the hash code for the key
     * @return the segment
    final Segment<k> segmentFor(int hash) {
        return segments[(hash >>> segmentShift) & segmentMask];
 // Put method in Segment:
 V put(K key, int hash, V value, boolean onlyIfAbsent) {
            try {
                int c = count;
                if (c++ > threshold) // ensure capacity
                HashEntry<k>[] tab = table;
                int index = hash & (tab.length - 1);
                HashEntry<k> first = tab[index];
                HashEntry<k> e = first;
                while (e != null && (e.hash != hash || !key.equals(e.key)))
                    e =;

                V oldValue;
                if (e != null) {
                    oldValue = e.value;
                    if (!onlyIfAbsent)
                        e.value = value;
                else {
                    oldValue = null;
                    tab[index] = new HashEntry<k>(key, hash, first, value);
                    count = c; // write-volatile
                return oldValue;
            } finally {

When we add any key value pair to ConcurrentHashMap, following steps take place:
  1. In ConcurrentHashMap, key can not be null. Key's hashCode method is used to calculate hash code
  2. Key 's HashCode method may be poorly written, so java developers have added one more method hash(Similar to HashMap) , another hash() function is applied and hashcode is calculated.
  3. Now we need to find index of segment first, For finding a segment for given key, above SegmentFor method is used.  
  4.  After getting Segment, we use segment's put method.While putting key value pair in Segment, it acquires lock, so no other thread can enter in this block and then it finds index in HashEntry array using hash &(tab.length-1).
  5. If you closely observe, Segment's put method is similar to HashMap's put method.


You want to put element in ConcurrentHashMap only when if it does not have Key already otherwise return old value. This can be written as:
if (map.get(key)==null)

    return map.put(key, value);
   return map.get(key);
Above operation is atomic if you use putIfAbsent method. This may be required behaviour. Lets understand with help of an example:
  1. Thread 1 is putting value in ConcurrentHashMap.
  2. At same time, Thread 2 is trying to read(get) value from ConcurrentHashMap and it may return null So it may override whatever thread 1 has put in ConcurrentHashMap.
Above behaviour may not be required so ConcurrentHashMap has putIfAbsent method.


     * {@inheritDoc}

     * @return the previous value associated with the specified key,

     *         or <tt>null</tt> if there was no mapping for the key

     * @throws NullPointerException if the specified key or value is null

    public V putIfAbsent(K key, V value) {
        if (value == null)
            throw new NullPointerException();
        int hash = hash(key.hashCode());
        return segmentFor(hash).put(key, hash, value, true);


get Entry:


     * Returns the value to which the specified key is mapped,
     * or {@code null} if this map contains no mapping for the key.
     * <p>More formally, if this map contains a mapping from a key
     * {@code k} to a value {@code v} such that {@code key.equals(k)},
     * then this method returns {@code v}; otherwise it returns
     * {@code null}.  (There can be at most one such mapping.)
     * @throws NullPointerException if the specified key is null
    public V get(Object key) {
        int hash = hash(key.hashCode());
        return segmentFor(hash).get(key, hash);

 /* Specialized implementations of map methods */

// get method in Segment:
        V get(Object key, int hash) {
            if (count != 0) { // read-volatile
                HashEntry<K,V> e = getFirst(hash);
                while (e != null) {
                    if (e.hash == hash && key.equals(e.key)) {
                        V v = e.value;
                        if (v != null)
                            return v;
                        return readValueUnderLock(e); // recheck
                    e =;
            return null;
Getting value from ConcurrentHashMap is straight forward.
  1. Calculate hash using key 's Hashcode
  2. Use segmentFor to get index of Segment.
  3. Use Segment's get function to get value corresponding to the key.
  4. If it does not find value in ConcurrentHashMap ,it locks the Segment and tries again to get the value.

Best Practice:

We should not use default constructor of ConcurrentHashMap if we require low level of Concurrency level as default ConcurrencyLevel is 16  and it will create 16 Segments by default.

We should use fully parameterized constructor:
ConcurrentHashMap(int initialCapacity,float loadFactor, int concurrencyLevel) 
In above constructor, initialCapacity and loadFactor is same as HashMap and concurrencyLevel is same as we have defined above.

So if you require only two threads that can write concurrently, you may initialise ConcurrentHashMap as:
 ConcurrentHashMap ch=new ConcurrentHashMap(16,0.75f,2);

ConcurrentHashMap will perform much better if you have few write threads and large number of read threads.

Please go through  core java interview questions for experienced for more interview questions.


Java tutorial for beginners Copyright © 2012