How To Best Implement Concurrent Hash Map in Java?

Last updated on Jun 19,2023 5.8K Views

How To Best Implement Concurrent Hash Map in Java?

edureka.co

This article will introduce you to a concept called as Concurrent Hash Map In Java and follow it up with a practical demonstration.Following pointers will be covered in this article,

Moving on with this article on Concurrent Hash Map in Java

How ConcurrentHashMap works internally?

From Java 5 onwards ConcurrentHashMap is introduced as an alternative for HashTable. We can also get a Synchronized map using the utility class method called synchronizedMap() but there is a drawback of this method i.e very poor performance as only a single thread can access it at one time. So ConcurrentHashMap addresses these issues.

Moving on with this article on Concurrent Hash Map in Java

Why other Map?

Even though we already have HashMap, HashTable then what is a need of ConcurrentHashMap, it is because it provides better performance at the same time it is thread-safe.

Moving on with this article on Concurrent Hash Map in Java

How it is different?

It is also based on hashing but its performance is improved by its locking strategy. Unlike HashTable or Synchronized HashMap it does not apply the same lock on each method it uses a separate lock for each method, It uses re-entrant lock for this purpose. Similar to HashMap, ConcurrentHashMap has 16 buckets i.e segments, to create ConcurrentHashMap with more than 16 buckets it has different constructors.

Before talking in detail let us review a few concepts below:

ConcurrentHashMap: This map allows concurrent thread access. Only part of the map called segment i.e underlying data structure is getting locked while adding or updating the map. It allows concurrent thread access to read the data without locking. It was introduced to improve performance.

Let’s see below diagram and try to understand how ConcurrentHashMap works.

So in the above diagram, we have 16 locks which lock only a portion of the map which is required so that other methods can be accessed by different threads thus improving performance.

Similar to HashMap, ConcurrentHashMap works in a similar way it contains 16 segments by default and stores element by hashing so if the elements have the same hash they are stored on the same segment as shown in the diagram above with the help of the linked list.

Moving on with this article on Concurrent Hash Map in Java

Difference between ConcurrentHashMap and HashMap

HashMap belongs to Collections while ConcurrentHashMap belongs to Concurrent Collections however there are many other differences between them.

As we have seen earlier for better performance, it consists of an array of nodes as table buckets which was table segments prior to Java 8.

The buckets are lazily initialized when the first insertion is performed. Every bucket can be locked independently by locking the first node of the bucket also read operations do not block.

Compared to HashMap, ConcurrentHashMap provides the extra concurrencyLevel argument to control the number of estimated threads to use.

Constructors:

  1. ConcurrentHashMap m=new ConcurrentHashMap();

    A new empty map is created with a default initial capacity of 16, load factor of 0.75 and concurrency level 16.

  2. ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity);
    A new empty map is created with a specified initial capacity, load factor of 0.75 and concurrency level 16.

  3. ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity, float loadFactor);

    A new empty map is created with a specified initial capacity and load factor with concurrency level 16.

  4. ConcurrentHashMap m=new ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel);
    A new empty map is created with a specified initial capacity, load factor and concurrency level.

  5. ConcurrentHashMap m=new ConcurrentHashMap(Map m);
    Creates new ConcurrentHashMap from provided map.

The other two arguments: initialCapacity and loadFactor worked quite the same as HashMap.
ConcurrentMap is memory consistent on key/value operations in a multi-threaded environment.

Moving on with this article on Concurrent Hash Map in Java

Pitfalls

While retrieving objects ConcurrentHashMap is not blocked and may overlap with update operations, thus for better performance they only retrieve most recently completed update operations.

Results of aggregate status methods including size, isEmpty, and containsValue are typically useful only when a map is not undergoing concurrent updates in other threads.

If concurrent updates are controlled properly these status methods can be reliable.

Although these methods do not guarantee in real-time.

The default table capacity is 16 however we can change it using concurrency level.

public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
//...
if (initialCapacity < concurrencyLevel) {
initialCapacity = concurrencyLevel;
}
//...
}

If keys keys are required to be in sorted order we can use ConcurrentSkipListMap.

Build stunning cross-platform mobile apps with our comprehensive Flutter Training.

Now after executing the above program you would have understood the Concurrent Hash Map in Java. Thus we have come to an end of this article on If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR A Comprehensive UI/UX Design Tutorial