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.

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.

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.

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.

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

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.

ConcurrentHashMap
ConcurrentHashMap

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.

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.

Conclusion

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

One thought on “Concurrenthashmap in Java with example”

Leave a Reply

Your email address will not be published. Required fields are marked *

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