Java Concurrent HashMap

·

3 min read

Introduction

The ConcurrentHashMap class provides a concurrent version of the standard HashMap. So its functionality is similar to a HashMap, except that it has internally maintained concurrency.

Depending upon the level of concurrency required the concurrent HashMap is internally divided into segments.

If the level of concurrency required is not specified then it takes 16 as the default value. So internally the ConcurrentHashMap will be divided into 16 segments. Each Segment behaves independently.

Why use Concurrent Hashmap

We use ConcurrentHashMap when a high level of concurrency is required. But already SynchronizedMap is present for this, so what advantages does ConcurrentHashMap have over the synchronized map.

Both are thread-safe. The major difference between the two is that in the case of synchronized map, every write operation acquires a lock on the entire SynchronizedMap while in the case of ConcurrentHashMap the lock is only on one of the segments.

So this the major performance booster for concurrent HashMap compared to the synchronized map.

ConcurrentHashMap

  1. If the concurrency level has been set explicitly, the ConcurrentHashMap gets divided into 16 segments and each segment acts as an independent HashMap.

  2. ConcurrentHashMap implements Map data structure and also provide thread safety like Hashtable.

  3. It works by dividing complete hashtable array into segments or portions and allowing parallel access to those segments.

  4. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

ConcurrentHashMap() : Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16).

ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>();

ConcurrentHashMap(int initialCapacity) : Creates a new, empty map with the specified initial capacity, and with default load factor (0.75) and concurrencyLevel (16).

ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity);

Synchronized Map :

From the below image you can see that the lock is on the entire HashMap Object. So the threads have to wait to acquire locks till the thread which has the lock completes its operation. So the performance is slow in the case of Synchronized HashMap.

image.png

Concurrent Map :

From the below image you can see that the lock is only on the segment. So the threads are free to access other segments that do not require a lock. So the performance is fast here.

image.png