Java/J2EE and SOA (346 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (17 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (343 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How To Best Implement Concurrent Hash Map in Java?

Published on Sep 11,2019 4K Views

21 / 22 Blog from Java Collections

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.

  • Concurrency-Level: It is a number which is an estimated number of concurrently updating threads.
  • Load-Factor: It is a value which is used to control the resizing factor.
  • Initial Capacity: It is a property which creates a Map with the size provided.

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

Image- Concurrent Hashmap- Edureka

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.

  • ConcurrentHashMap is Thread-safe i.e synchronized but HashMap is non-synchronized.
  • ConcurrentHashMap is low on performance because it is synchronized because sometimes threads have to wait but HashMap is high on performance because it is non-synchronized and any threads can access it simultaneously.
  • We will get ConcurrentModificationException if two threads are simultaneously trying to modify or add contents of Object. However, in the case of ConcurrentHashMap we won’t get any exception while performing the same operation.

  • Null values are allowed for key and values in HashMap however, ConcurrentHashMap does not allow null values for key and value it tried to add null value we will get exception i.e NullPointerException.

  • HashMap is introduced in JDK 1.2 whereas ConcurrentHashMap is introduced in JDK 1.5.

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.

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 Certification Training Course
Course NameDate
Java Certification Training Course

Class Starts on 28th January,2023

28th January

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 25th February,2023

25th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How To Best Implement Concurrent Hash Map in Java?

edureka.co