How Does ConcurrentHashMap Achieve Thread-Safety in Java?
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
import java.util.*;
import java.util.concurrent.*;
class GFG extends Thread {
static HashMap m = new HashMap();
public void run()
{
try {
Thread.sleep( 2000 );
}
catch (InterruptedException e) {
}
System.out.println( "Child Thread updating Map" );
m.put( 103 , "C" );
}
public static void main(String arg[])
throws InterruptedException
{
m.put( 101 , "A" );
m.put( 102 , "B" );
GFG t = new GFG();
t.start();
Set s1 = m.keySet();
Iterator itr = s1.iterator();
while (itr.hasNext()) {
Integer I1 = (Integer)itr.next();
System.out.println(
"Main Thread Iterating Map and Current Entry is:"
+ I1 + "..." + m.get(I1));
Thread.sleep( 3000 );
}
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
import java.util.*;
import java.util.concurrent.*;
class Main extends Thread {
static ConcurrentHashMap<Integer, String> m
= new ConcurrentHashMap<Integer, String>();
public void run()
{
try {
Thread.sleep( 2000 );
}
catch (InterruptedException e) {
}
System.out.println( "Child Thread updating Map" );
m.put( 103 , "C" );
}
public static void main(String arg[])
throws InterruptedException
{
m.put( 101 , "A" );
m.put( 102 , "B" );
Main t = new Main();
t.start();
Set<Integer> s1 = m.keySet();
Iterator<Integer> itr = s1.iterator();
while (itr.hasNext()) {
Integer I1 = itr.next();
System.out.println(
"Main Thread Iterating Map and Current Entry is:"
+ I1 + "..." + m.get(I1));
Thread.sleep( 3000 );
}
System.out.println(m);
}
}
|
Output
Main 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 |
Last Updated :
12 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...