Concurrent Hashmaps: How does it work internally?

Recently I was reading more on how Concurrent Hashmaps works internally and how is it different from Hashmap or Hashtable. I have consolidated a small write up for each one of us to understand. Please let me know if there are any mistakes in my understanding (I will happily edit it)

Before we dig further, lets know more about ConcurrentHashMap. ConcurrentHashMap is an alternative of Hashtable in Java, which is a synchronized collection class. On the contrary, ConcurrentHashMap is a thread-safe collection and is used as a primary Map implementation for multi-threaded and Concurrent environment

There are some subtle differences between ConcurrentHashMap, Hashtable and Collections.synchronizedMap(Map)

  • Hashtable is an old implementation extending to Dictionary class earlier and later realigned to Map interface. Though it is synchronized, it has a lot of scalability issues
  • Collections.synchronizedMap(map) works exactly like ConcurrentHashMap. Then why do we need it? Well, It will block the Map during an operation and hence degrades performance but ensures data consistency. We can use this if we want each thread to take updated data
  • ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them.

Now, as per how to works internally, if you see the constructor of ConcurrentHashMap, it reads the below code

public ConcurrentHashMap (int initialCapacity, float loadFactor, int concurrencyLevel)

It first creates a new, empty map with the specified initial capacity, load factor and concurrency level.

  • Concurrency level defines the estimated number of concurrently updating threads
  • While, initialCapacity performs the internal sizing of the map.

If you check the ConcurrentHashMap API, both the values are set to 16 by default. So, unlike Hashtable or Collections.synchronizedMap(map), where it maintains a map wide lock, ConcurrentHashMap maintains 16 locks, indicating the 16 threads at concurrencyLevel.

Retreival Operations like get do not block the map anyway, so it may overlap with an update operation. Considering the design, we can perform any operation without locking the entire map

To view or add a comment, sign in

Others also viewed

Explore content categories