How Does ConcurrentHashMap Achieve Thread-Safety in Java?
Last Updated :
12 Aug, 2022
ConcurrentHashMap is a hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specifications as Hashtable and includes all methods of Hashtable. ConcurrentHashMap is in java.util.Concurrent package.
Syntax:
public class ConcurrentHashMap<K,V>
extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable
Where K refers to the type of keys maintained by this map, and V refers to the type of mapped values
Need of ConcurrentHashmap:
- Though HashMap has a lot of advantages, it can’t be used for multithreading because it is not Thread-safe.
- Even though Hashtable is considered to be thread-safe, it has some disadvantages. For example, Hashtable requires lock for reading open even though it doesn’t affect the object.
- In HashMap, if one thread is iterating over an object, another thread is trying to access the same object, it throws ConcurrentModificationException, whereas concurrent hashmap doesn’t throw ConcurrentModificationException.
How it made possible to make ConcurrentHashMap thread-safe?
- The java.util.Concurrent.ConcurrentHashMap class achieves thread-safety by dividing the map into segments, the lock is required not for the entire object but for one segment, i.e one thread requires a lock of one segment.
- In ConcurrentHashap the read operation doesn’t require any lock.
Example 1:
Java
// Java Program to llustarte ConcurrentModificationException
// Using Normal Collections
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Main class extending Thread class
class GFG extends Thread {
// Creating a static HashMap class object
static HashMap m = new HashMap();
// run() method for the thread
public void run()
{
// Try block to check for exceptions
try {
// Making thread to sleep for 3 seconds
Thread.sleep(2000);
}
// Catch block to handle exceptions
catch (InterruptedException e) {
}
// Display message
System.out.println("Child Thread updating Map");
// Putting element in map
m.put(103, "C");
}
// Method 2
// Main driver method
public static void main(String arg[])
throws InterruptedException
{
// Adding elements to map object created above
// using put() method
m.put(101, "A");
m.put(102, "B");
// Creating thread inside main() method
GFG t = new GFG();
// Starting the thread
t.start();
// Operating keySet() method and
// storing it in Set class object
Set s1 = m.keySet();
// Iterating over Set class object
// using iterators
Iterator itr = s1.iterator();
// Holds true till there is single element present
// inside object
while (itr.hasNext()) {
// traversing over elements in object
// using next() method
Integer I1 = (Integer)itr.next();
// Print statement
System.out.println(
"Main Thread Iterating Map and Current Entry is:"
+ I1 + "..." + m.get(I1));
// Making thread to sleep for 3 seconds
Thread.sleep(3000);
}
// Printing all elements on console
System.out.println(m);
}
}
Output:
Main Thread Iterating Map and Current Entry is:101...A
Child Thread updating Map
Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1493)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1516)
at Main.main(Main.java:30)
Output explanation:
class used in the above program extends Thread class. Let us do see control flow. So, Initially, the above java program contains one thread. When we encounter the statement Main t= new Main(), we are creating an object for a class that is extending the Thread class.so, whenever we call t.start() method the child thread gets activated and invokes run() method. Now main thread starts executing, whenever the child thread updates the same map object, it will throw an exception named ConcurrentModificationException.
Now let us modify the above program by using ConcurrentHashMap in order to resolve the above exception been generated while executing the above program.
Example 2:
Java
// Java Program to llustarte ConcurrentModificationException
// Using ConcurrentHashMap
// Importing required classes
import java.util.*;
import java.util.concurrent.*;
// Main class extending Thread class
class Main extends Thread {
// Creating static concurrentHashMap object
static ConcurrentHashMap<Integer, String> m
= new ConcurrentHashMap<Integer, String>();
// Method 1
// run() method for the thread
public void run()
{
// Try block to check for exceptions
try {
// Making thread to sleep for 2 seconds
Thread.sleep(2000);
}
// Catch block to handle the exceptions
catch (InterruptedException e) {
}
// Display message
System.out.println("Child Thread updating Map");
// Inserting element
m.put(103, "C");
}
// Method 2
// Main driver method
public static void main(String arg[])
throws InterruptedException
{
// Adding elements to object created of Map
m.put(101, "A");
m.put(102, "B");
// Creating thread inside main() method
Main t = new Main();
// Starting thread
t.start();
// Creating object of Set class
Set<Integer> s1 = m.keySet();
// Creating iterator for traversal
Iterator<Integer> itr = s1.iterator();
// Condition holds true till there is single element
// in Set object
while (itr.hasNext()) {
// Iterating over elements
// using next() method
Integer I1 = itr.next();
// Display message
System.out.println(
"Main Thread Iterating Map and Current Entry is:"
+ I1 + "..." + m.get(I1));
// Making thread to sleep for 3 seconds
Thread.sleep(3000);
}
// Display elements of map objects
System.out.println(m);
}
}
OutputMain Thread Iterating Map and Current Entry is:101...A
Child Thread updating Map
Main Thread Iterating Map and Current Entry is:102...B
Main Thread Iterating Map and Current Entry is:103...C
{101=A, 102=B, 103=C}
Output explanation:
the Class used in the above program extends Thread class. Let us see control flow, so as we know that in ConcurrentHashMap while one thread is iterating the remaining threads are allowed to perform any modification in a safe manner. In the above program Main thread is updating Map, at the same time child thread is also trying to update the Map object. This Program will not throw ConcurrentModificationException.
Differences Between Hashtable, Hashmap, ConcurrentHashmap
HashTable
| HashMap
| ConcurrentHashMap
|
---|
We will get Thread-safety by locking whole map object. | It is not Thread-safe. | We will get Thread-safety without locking Total Map object just with segment level lock. |
Every read and write operation requires an objectstotal map object lock. | It requires no lock. | Read operations can be performed without lock but write operations can be performed with segment level lock. |
At a time only one thread is allowed to operate on map(Synchronized) | At a time multiple threads are not allowed to operate. It will throw an exception | At a time multiple threads are allowed to operate on map objects in a safe manner |
While one thread iterates Map object, the other Threads are not allowed to modify the map otherwise we get ConcurrentModificationException | While one thread iterates Map object, the other Threads are not allowed to modify the map otherwise we get ConcurrentModificationException | While one thread iterates Map object, the other Threads are allowed to modify the map and we won’t get ConcurrentModificationException |
Null is not allowed for both keys and values | HashMap allows one null key and multiple null values | Null is not allowed for both keys and values. |
Introduced in 1.0 version | Introduced in 1.2 version | Introduced in 1.5 version |
Similar Reads
How to Create a Thread-Safe ConcurrentHashSet in Java? Creating Thread Safe ConcurrentHashSet is not possible before JDK 8 because of the java.util.concurrent package does not have a class called ConcurrentHashSet, but starting with JDK 8, the newly added keySet (the default) and newKeySet() methods to create a ConcurrentHashSet in Java that is supporte
4 min read
Java Thread Safety and How to Achieve it? As we know Java has a feature, Multithreading, which is a process of running multiple threads simultaneously. When multiple threads are working on the same data, and the value of our data is changing, that scenario is not thread-safe and we will get inconsistent results. When a thread is already wor
5 min read
ConcurrentHashMap get() Method in Java The get() method in Java's ConcurrentHashMap class is used to retrieve the value associated with a given key. It has the following signature: V get(Object key) where: key is the key whose associated value is to be retrieved.The get() method works in a concurrent environment, which means that it can
3 min read
ConcurrentHashMap get() Method in Java The get() method in Java's ConcurrentHashMap class is used to retrieve the value associated with a given key. It has the following signature: V get(Object key) where: key is the key whose associated value is to be retrieved.The get() method works in a concurrent environment, which means that it can
3 min read
ConcurrentHashMap compute() method in Java with Examples The compute(Key, BiFunction) method of ConcurrentHashMap class is used to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). This method is used to atomically update a value for given key in ConcurrentHashMap.If the remapping funct
3 min read
ConcurrentHashMap containsKey() Method in Java The containsKey() method in Java's ConcurrentHashMap class is used to determine whether the map contains a given key. It has the following signature: boolean containsKey(Object key) where: key is the key to be searched for in the map. The containsKey() method works in a concurrent environment, which
3 min read