Java – ConcurrentHashMap Class

ConcurrentHashMap class is introduced in JDK 1.5, which implements ConcurrentMap as well as Serializable interface also.

This was introduced to handle situations like running in multithreaded environment and also it works fine when you try to modify map at runtime i.e. it allows modification at runtime and avoid ConcurrentModificationException.

When threads are involved, ConcurrentHashMap is a better option over a regular HashMap. The underlying data structure for ConcurrentHashMap is also the Hashtable.

It provides thread safety and allows concurrent access to the map

  • Concurrency-Level : Defines the number which is an estimated number of concurrently updating threads. The implementation performs internal sizing to try to accommodate this many threads. Default concurrency-level of ConcurrentHashMap is 16.
  • Load-Factor : It’s a threshold, used to control resizing.
  • Initial Capacity : The implementation performs internal sizing to accommodate these many elements.
  • Segments :A ConcurrentHashMap is divided into number of segments
  • Null cannot be inserted as key or value in ConcurrentHashMap.

Note : A ConcurrentHashMap has internal final class called Segment so we can say that ConcurrentHashMap is internally divided in segments of size 16, so at max 16 threads can work at a time. It means each thread can work on a each segment during high concurrency and atmost 16 threads can operate at max which simply maintains 16 locks to guard each bucket of the ConcurrentHashMap.

In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updation in object, thread must lock the particular segment in which thread want to operate.This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time 16 updation operations can be performed by threads.

A method Highlight : putIfAbsent(K key, V value)

This method puts the key only if it is not already present in the map.

Coding Example
import java.util.concurrent.*;
class ExampleConcurrentHashMap {
    public static void main(String[] args)
    {
        ConcurrentHashMap chmap = new ConcurrentHashMap();
        chmap.put(1, "Hi");
        chmap.put(2, "Programmer");
        chmap.put(3, "Today");
  
        // Here we can't add “Whatsup” because key “2”
        // is already present in ConcurrentHashMap object
        chmap.putIfAbsent(2, "Whatsup");
  
        // Now we can add "Whatsup"
        chmap.putIfAbsent(4, "Whatsup");
          
        System.out.println(chmap);
    }
}
        

Output

{1=Hi, 2=Programmer, 3=Today, 4=Whatsup}

Constructors of ConcurrentHashMap

HashMap provides 5 constructors :

  • ConcurrentHashMap() : Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16).
  • ConcurrentHashMap(int initialCapacity) : Creates a new, empty map with the specified initial capacity, and with default load factor (0.75) and concurrencyLevel (16).
  • ConcurrentHashMap(int initialCapacity, float loadFactor) : Creates a new, empty map with the specified initial capacity and load factor and with the default concurrencyLevel (16).
  • ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) : Creates a new, empty map with the specified initial capacity, load factor and concurrency level.
  • ConcurrentHashMap(Map map) : Creates a new map with the same mappings as the given map.

When to use ConcurrentHashMap in Java

ConcurrentHashMap is best suited when you have multiple readers and few writer. The performance of ConcurrentHashMap effectively reduces if the writers are more than the readers.

But why does the performance reduces ? The reason for this is that you got to lock all portion of Map, and effectively each reader will wait for another writer, operating on that portion of Map. ConcurrentHashMap is a good choice for caches, which can be initialized during application start up and later accessed my many request processing threads.

Difference between ConcurrentHashMap and HashMap | when to you use what ?

S.NoConcurrentHashMapHashMap
1ConcurrentHashMap is thread-safe and can be used in a concurrent environment without external synchronization.Not thread-safe, not good for multithreaded functionalities
2in case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular portion instead of locking the whole Map.You can make HashMap synchronized by wrapping it on Collections.synchornizedMap(HashMap) which will return a collection which is almost equivalent to Hashtable, where every modification operation on Map is locked on Map object
3ConcurrentHashMap is more scalable and performs better than Synchronized HashMap in the multi-threaded environment.in Single threaded environment both HashMap and ConcurrentHashMap gives comparable performance, where HashMap only slightly better.
4Whereas In ConcurrentHashMap we wont get any exception while performing any modification at the time of Iteration.While one thread is Iterating the HashMap object, if other thread try to add/modify the contents of Object then we will get Run-time exception saying ConcurrentModificationException.

 Important Summary

  1. Choose concurrency level carefully as a significantly higher number can be a waste of time and space and the lower number may introduce thread contention in case writers over number concurrency level.
  2. Iterator returned by ConcurrentHashMap is weekly consistent, fail-safe and never throw ConcurrentModificationException. In Java.
  3. You can use ConcurrentHashMap in place of Hashtable but with caution as CHM doesn’t lock whole Map.

Leave a Comment