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
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read