Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How Does ConcurrentHashMap Achieve Thread-Safety in Java?

  • Last Updated : 26 Oct, 2021

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:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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.
  • n 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 ConcurrenHashap 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()) {
  
            // traversign 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);
    }
}
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 exceptionAt  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 ConcurrentModificationExceptionWhile one thread iterates Map object, the other Threads are not allowed to modify the map otherwise we get ConcurrentModificationExceptionWhile 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 valuesHashMap allows one null key and multiple null valuesNull is not allowed for both keys and values.
Introduced in 1.0 versionIntroduced in 1.2 versionIntroduced in 1.5 version



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!