In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to achieve thread safety in ConcurrentHashMap in Java". In daily operation, I believe that many people have doubts about how to achieve thread safety in Java. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the question of "how does ConcurrentHashMap achieve thread safety in Java?" Next, please follow the editor to study!
Syntax:
Public class ConcurrentHashMapextends AbstractMapimplements ConcurrentMap, Serializable
Where K refers to the type of key maintained by this mapping, and V refers to the type of mapping value.
Requirements for ConcurrentHashmap:
Although HashMap has many advantages, it cannot be used with multithreading because it is not thread-safe.
Although Hashtable is considered thread-safe, it also has some disadvantages. For example, Hashtable requires a lock to read and open, even if it does not affect the object.
N HashMap, if one thread is iterating over an object and another thread is trying to access the same object, it throws ConcurrentModificationException, while concurrent hashmap does not throw ConcurrentModificationException.
How to make ConcurrentHashMap thread safety possible?
The java.util.Concurrent.ConcurrentHashMap class achieves thread safety by dividing map into segment. Not the whole object needs a lock, but a segment, that is, a thread needs a segment lock.
In ConcurrenHashap, no locks are required for read operations.
Example 1:
Import java.util.*;import java.util.concurrent.*;// extends the main class of the Thread class class GFG extends Thread {/ / creates a static HashMap class object static HashMap m = new HashMap (); public void run () {/ / try block checks for exceptions try {/ / makes the thread sleep for 3 seconds Thread.sleep (2000);} catch (InterruptedException e) {} System.out.println ("child thread update mapping") M.put (103C);} public static void main (String arg []) throws InterruptedException {m.put (10101A "); m.put (102B"); 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 iterative mapping and current entries are:" + I1 + "..." + m.get (I1)); Thread.sleep (3000);} System.out.println (m);}}
Output:
The main thread iteration mapping and the current entry are: 101. A
Child thread update 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)
Output description:
The class used in the above program extends the Thread class. Let's take a look at the control flow. So, initially, the above java program contains a thread. When we encounter the statement Main t = new Main (), we are creating an object for a class that extends the Thread class. Therefore, every time we call the t.start () method, the child thread is activated and the run () method is called. Now the main thread starts to execute, throwing an exception called ConcurrentModificationException whenever the child thread updates the same map object.
Now let's use ConcurrentHashMap to modify the above program to resolve the exceptions that occur when the above program is executed.
Example 2:
Import java.util.*;import java.util.concurrent.*;class Main extends Thread {static ConcurrentHashMap m = new ConcurrentHashMap (); public void run () {try {Thread.sleep (2000);} catch (InterruptedException e) {} System.out.println ("child thread update mapping"); m.put (103C);} public static void main (String arg []) throws InterruptedException {m.put (101A) M.put; Main t = new Main (); t.start (); Set S1 = m.keySet (); Iterator itr = s1.iterator (); while (itr.hasNext ()) {Integer I1 = itr.next (); System.out.println ("main thread iterative mapping and current entry is:" + I1 + "..." + m.get (I1)); Thread.sleep (3000) } System.out.println (m);}}
Output
The main thread iteration mapping and the current entry are: 101. A
Child thread update mapping
The main thread iteration mapping and the current entry are: 102. B
The main thread iteration mapping and the current entry are: 103. C
{101cm A, 102B, 103C}
Output description:
The Class used in the above program extends the Thread class. Let's look at the control flow, so we know that in ConcurrentHashMap, when a thread is iterating, the remaining threads can perform any changes in a safe manner. In the above program, the main thread is updating the Map, while the child thread is also trying to update the Map object. This program will not throw ConcurrentModificationException.
The difference between Hashtable, Hashmap, and ConcurrentHashmap HashtableHashmapConcurrentHashmap We will achieve thread safety by locking the entire map object. It is not thread safe. We will get thread safety without using segment-level locks to lock the Total Map object. Each read and write operation requires an objectstotal mapping object lock. It doesn't need to be locked. Read operations can be performed unlocked and write operations can be performed with segment-level locks. Only one thread is allowed to operate on the map at a time (synchronization) does not allow multiple threads to run at the same time. It throws an exception that allows multiple threads to operate on the map object in a safe manner at a time when one thread iterates the Map object, other threads are not allowed to modify the mapping, otherwise we get ConcurrentModificationException when one thread iterates the Map object, other threads are not allowed to modify the mapping, otherwise we get ConcurrentModificationException when one thread iterates the Map object, other threads are allowed to modify the map. We will not get ConcurrentModificationException keys and values are not allowed for NullHashMap to allow a null key and multiple null keys and values are not allowed to be Null. Introduced in version 1.0, introduced in version 1.2 and introduced in version 1.5, the study on "how to achieve thread safety in ConcurrentHashMap in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.