“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”

🌊 author’s home page: Haichong 🌊 Author Profile: πŸ₯‡HDZ core group member, πŸ† full stack quality creator, 🌊 has been ranked top ten in the weekly list of C station for a second year. Fan welfare: Send four books to fans every week (each one has), and send various small gifts every month (gold boring enamelware cup, pillow, mouse pad, mug, etc.)

ConcurrentHashMap is a hash table that supports full concurrency for retrieval and high expected concurrency for updates. This class follows the same functional specification as Hashtable and contains all the methods of Hashtable. ConcurrentHashMap is in the java.util.concurrent package.

Grammar:

public class ConcurrentHashMap<K.V>
extends AbstractMap<K.V>
implements ConcurrentMap<K.V>, Serializable
Copy the code

Where K refers to the type of the key maintained by the map and V refers to the type of the map value

ConcurrentHashmap needs:

  • While HashMap has many advantages, it cannot be used for multithreading because it is not thread-safe.
  • Although Hashtable is considered thread-safe, it has some disadvantages. For example, Hashtable needs to be locked to read open, even if it does not affect objects.
  • N HashMap, if a thread is iterative an object that another thread attempts to access the same object, it will throw ConcurrentModificationException, The concurrent hashmap ConcurrentModificationException.

How do I make ConcurrentHashMap thread safe?

  • Java. Util. Concurrent. ConcurrentHashMap class by the map is divided into segment thread-safe, not the entire object needs to lock, but a segment, that is, a thread needs a segment of the lock.
  • In ConcurrenHashap, read operations do not require any locks.

Example 1:

import java.util.*;
import java.util.concurrent.*;

// Extend the main class of Thread
class GFG extends Thread {

	// Create static HashMap class objects
	static HashMap m = new HashMap();

	public void run(a)
	{

		// The try block checks for exceptions
		try {

			// Let the thread sleep for 3 seconds
			Thread.sleep(2000);
		}
		catch (InterruptedException e) {
		}
		System.out.println("Child thread update 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 iteration map and current entry are :"
				+ I1 + "..." + m.get(I1));
			Thread.sleep(3000); } System.out.println(m); }}Copy the code

Output:

The main thread iteration map and the current entry are:101.. A Child thread updates mapping 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)
Copy the code

Output description:

The class used in the above program extends the Thread class. Let’s look at control flow. So, initially, the Java program above contains a thread. When we encounter the statement Main t= new Main(), we are creating an object for the class that extends Thread. Therefore, whenever we call the t.start() method, the child thread gets activated and calls the run() method. The main thread now, when the child thread to update the same map object, will throw an exception called ConcurrentModificationException.

Now let’s use ConcurrentHashMap to modify the above program to resolve the exception generated during execution of the above program.

Example 2:

import java.util.*;
import java.util.concurrent.*;

class Main extends Thread {
	static ConcurrentHashMap<Integer, String> m
		= new ConcurrentHashMap<Integer, String>();
	public void run(a)
	{
		try {
			Thread.sleep(2000);
		}
		catch (InterruptedException e) {
		}
		System.out.println("Child thread update 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 iteration map and current entry are :"
				+ I1 + "..." + m.get(I1));
			Thread.sleep(3000); } System.out.println(m); }}Copy the code

The output

The main thread iteration map and the current entry are:101.. A subthread update map main thread iteration map and current entry are:102.. B Main thread iteration map and current entry are:103...C
{101=A, 102=B, 103=C}
Copy the code

Output description:

The Class used in the above program extends the Thread Class. Let’s look at control flow, so we know that in ConcurrentHashMap, while one thread is iterating, the remaining threads can perform any modifications in a safe manner. The main thread is updating the Map and the child thread is trying to update the Map object. This procedure ConcurrentModificationException.

Hashtable, Hashmap, ConcurrentHashmap

Hashtable Hashmap ConcurrentHashmap
We will achieve thread-safety by locking the entire map object. It is not thread-safe. We will achieve thread-safety without having to use segment-level locks to lock the Total Map object.
Each read/write operation requires an ObjectStotal mapping object lock. It doesn’t need a lock. Read operations can be performed without a lock and write operations can be performed with a segment-level lock.
Allows only one thread to operate on the map at a time (synchronization) Multiple threads are not allowed to run simultaneously. It throws an exception Allows multiple threads to manipulate map objects in a safe manner at once
When a thread iterative Map object, other threads are not allowed to modify the mapping, otherwise we will get ConcurrentModificationException When a thread iterative Map object, other threads are not allowed to modify the mapping, otherwise we will get ConcurrentModificationException When a thread iterative Map object, other threads are allowed to modify the Map, we won’t get ConcurrentModificationException
Neither key nor value can be Null A HashMap allows one empty key and multiple null values Neither key nor value can be Null.
Introduced in version 1.0 Introduced in version 1.2 Introduced in version 1.5

Write it at the end

I’ve been writing a technology blog for a long time, mostly via nuggets, and this is my article on how ConcurrentHashMap in Java is thread safe. I like to share technology and happiness through articles. You can visit my blog at juejin.cn/user/204034… For more information. Hope you like it! 😊

πŸ’Œ welcomes your comments and suggestions in the comments section! πŸ’Œ