Concurrenthashmap in Java with example

This guide will help you to understand the concept Concurrenthashmap in Java.

Additionally, we will also take a look at Concurrenthashmap internal implementation and difference between Concurrenthashmap, HashMap, and HashTable.

What you will Learn
  • What is Concurrenthashmap in Java?
  • Why is Concurrenthashmap is thread-safe?
  • When do we need Concurrenthashmap over HashMap or HashTable?
  • How do you use Concurrenthashmap using an example?
  • What is Concurrenthashmap in Java?

Introduction to ConcurrentHashMap in Java?

What is the concurrent hash map? 

How does it work? 

How it is different from HashTable?

Well…If you are going to attend a java interview then there are chances that you will be asked a few questions about java concurrent package.

And ConcurrentHashMap is an important class present in java.util.concurrent package.

What is ConcurrentHashMap?

ConcurrentHashMap was introduced in Java 1.5, is a part of Java concurrent package (java.util.concurrent).

Concurrent Hash Map was introduced as an alternative for HashTable to improve the performance of key-value based data structure in a multithreaded environment.

Although the Concurrent hash map looks very similar to HashTable, there is a huge difference in their internal implementation.

Unlike HashTable, ConcurrentHashMap doesn’t lock the map when you are retrieving the data from it.

In addition to that, ConcurrentHashMap also doesn’t lock the entire map when you writing data into it.

Internally concurrent hash map locks only the part (bucket) where the data is being written to.

ConcurrentHashMap class inherits from AbstractMap and it implements ConcurrentHashMap interface.

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

Key Characteristics of ConcurrentHashMap

  • ConcurrentHashMap is the thread-safe version of HashMap that means the ConcurrentHashMap can be a preferable option in a concurrent environment.

Difference between HashMap, ConcurrentHashMap, and HashTable

HashMap allows multiple threads to operate simultaneously.

Therefore, there are chances of data-insistency when multiple threads are performing some operation on HashMap.

HashMap Internal Implementation
HashMap Internal Implementation

Hence HashMap is not preferable (not thread-safe) in a multi-threaded environment.

Coming to the Hash Table.

HashTable is a thread-safe key-value based data structure.

That means at a time only one thread can perform some operations on HashTable.

Then why HashTable is not good even in multi-threaded scenarios?.

Let’s take a look at the HashTable's code.

public synchronized boolean isEmpty() {
        return count == 0;
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();

        addEntry(hash, key, value, index);
        return null;

public synchronized V get(Object key) {
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<?,?> e = tab[index] ; e != null ; e = {
            if ((e.hash == hash) && e.key.equals(key)) {
                return (V)e.value;
        return null;

If you look at the above HashTable's source code, you may notice that all put, get, and isEmpty functions are synchronized.

That means if one thread is doing some operation on HashTable, then other thread can’t even call isEmpty() to check whether HashTable is empty or not.

Hence we can conclude that performance-wise Hashtable is not a good option.

But how ConcurrentHashMap is good in performance?

ConcurrentHashMap in java is very similar to HashTable but it was introduced to overcome those performance issues.

To know how ConcurrentHashMap is good in performance, let’s look into the internal implementation of the ConcurrentHashMap.

public class ConcurrentHashMap<K,V> implements ConcurrentMap<K,V>

Basically, ConcurrentHashMap implements ConcurrentMap which provides a guarantee to thread safety and atomicity.

That means ConcurrentHashMap also uses the basic principles of HashMap including Hashing, Bucket, etc.

ConcurrentHashMap internally uses the bucket to store data, and the default size of the buckets is 16.

Similar to HashMap, the main methods of ConcurrentHashMap class are:

public V put(K key, V value)
public V get(Object key)
public V remove(Object key)
public boolean containsKey(Object key)

How ConcurrentHashMap represent a single Data element

ConcurrentHashMap internally usage an inner class Node to represent the data.

 static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        volatile V val;
        volatile Node<K,V> next;

The Node class is a simple class that represents the key and value of the data.

volatile Node<K,V> next;

If you look at the above statement, you may notice that the Node also contains the reference of the next Node element.

That means inside one bucket, ConcurrentHashMap stores all the elements like a linked list.

Now as we have a fair understanding of how ConcurrentHashMap uses Node class to represents a single data element.

How ConcurrentHashMap Save a Data Element in the Bucket

As we know that by default ConcurrentHashMap uses segment array (default size of the array is 16).

Unlike HashTable, ConcurrentHashMap provides better performance by replacing HashTable's Map wide lock into Segment wide locks.

Instead of locking the complete map itself, ConcurrentHashMap’s put operation only locks an index of the segment array.


Therefore, by default in ConcurrentHashMap, there could be 16 Segment locks, hence thread operating in one segment index won’t affect other elements present in a different segment.

To conclude, we can say that 16 different threads can perform add/update operations simultaneously in the concurrentHashMap.

The segment in ConcurrentHashMap.
The segment in ConcurrentHashMap.
How to change Segment Size

Segment array size decides how many threads can perform put operation simultaneously on ConcurrentHashMap.

ConcurrentHashMap<String, String> concurrentMap = new ConcurrentHashMap<>(20, 0.75f, 5);

In the above example, 20 is initialCapacity, 0.75f is loadFactor, and 5 is concurrencyLevel.

initialCapacity specifies how many elements concurrent hash map may have to accommodate this many (20) elements.

loadFactor is 0.75f which means once the map size exceeds 15 (20*.75=15), then it is time to increase the map size.

concurrencyLevel decides the size of the segment array. In our example, we have specified the concurrencyLevel 10 that means at a given point of time segment size would be 10 or more than 10.

To calculate segment size we use the formula 2X >= concurrencyLevel.

Size of segment array = 2X >= 10 = 16.

Therefore segment size would be 16.

How get operation performed in ConcurrentHashMap

Get operation in ConcurrentHashMap
Get operation in ConcurrentHashMap

One of the best features of ConcurrentHashMap is any number of threads can perform read operations.

ConcurrentHashMap doesn’t lock a segment while performing a get operation.

ConcurrentHashMap (CHM) example

Before writing an example, it is good to know that CHM doesn’t allow null key or value.

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.concurrent.ConcurrentHashMap.putVal(
	at java.base/java.util.concurrent.ConcurrentHashMap.put(
	at com.codedelay.corejava.ConcurrentHashMapDemo.main(
package com.codedelay.corejava;

import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class ConcurrentHashMapDemo {

	public static void main(String[] args) {
		Student s1 = new Student(1001, "Mark");
		Student s2 = new Student(1001, "Adam");
		Student s3 = new Student(1001, "Sara");
		Student s4 = new Student(1001, "Mathew");
		Student s5 = new Student(1001, "John");
		//Put operation
		ConcurrentHashMap<Integer, Student> concurrentMap = new ConcurrentHashMap<>(20, 0.75f, 5);
		concurrentMap.put(1, s1);
		concurrentMap.put(2, s2);
		concurrentMap.put(3, s3);
		concurrentMap.put(4, s4);
		concurrentMap.put(5, s5);
		//retrive value from concurrentHashMap
		for (Map.Entry<Integer, Student> e : concurrentMap.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
package com.codedelay.corejava;

public class Student {
	private int studentId;
	private String studentName;
	public Student(int studentId, String studentName) {
		this.studentId = studentId;
		this.studentName = studentName;
	public int getStudentId() {
		return studentId;
	public String getStudentName() {
		return studentName;
	public String toString() {
		return "Student [studentId=" + studentId + ", studentName=" + studentName + "]";


In this tutorial, we discussed ConcurrentHashMap in java and it’s internal implementation.

Click to rate this post!
[Total: 1 Average: 5]

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.