In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you "Java multithreading high concurrency in how to solve ArrayList and HashSet and HashMap unsafe problems", the content is easy to understand, clear, hope to help you solve doubts, the following let Xiaobian lead you to study and learn "Java multithreading high concurrency in how to solve the problem of ArrayList and HashSet and HashMap unsafe" this article.
Thread unsafe solution of 1.ArrayList
Open the comment on the first line of the main method and execute it a few more times, and you will see an exception message such as the following figure:?
This is a concurrent modification exception. First of all, ArrayList must be thread unsafe. The reason for this exception is that it is possible that when the first thread enters the ArrayList collection to perform add operations, another thread also comes in for add operations, and the third thread comes in for get operations, resulting in no way to synchronize reads and writes, and finally explodes when printing the results.
The solution looks at the remaining lines of comments in the code.
Package test.notsafe; import java.util.*;import java.util.concurrent.CopyOnWriteArrayList; / * demonstrate ArrayList thread unsafe problems and solutions * / public class ThreadDemo2 {public static void main (String [] args) {/ / List list = new ArrayList (); / / solution 1: use Vector / / List list = new Vector () / / solution 2:Collections / / List list = Collections.synchronizedList (new ArrayList ()); / / solution 3:CopyOnWriteArrayList List list = new CopyOnWriteArrayList (); for (int I = 0; I
< 10; i++) { new Thread(() ->{list.add (UUID.randomUUID (). ToString (). Substring (0J8)); System.out.println (list);}, String.valueOf (I). Start ();}
A simple explanation for solving thread unsafety problems with CopyOnWriteArrayList: take a look at the add (E e) method in the source code:
Public boolean add (E e) {final ReentrantLock lock = this.lock; lock.lock (); try {Object [] elements = getArray (); int len = elements.length; Object [] newElements = Arrays.copyOf (elements, len + 1); newElements [len] = e; setArray (newElements); return true } finally {lock.unlock ();}}
Before adding add, the CopyOnWriteArrayList locks the lock, then obtains the original ArrayList collection container through getArray (), then calls the Arrays.copyOf method to copy the original container out of a new container, because it needs to be added (the length is naturally + 1), and then adds elements to the new container. After the addition is completed, the setArray method is called to point the reference to the original container to the new container. Then the advantage of this is: add elements to the new container, what the original container should be, and other threads will read the elements from the original container if they want to get (that is, multiple threads can read them concurrently); while other threads need to add add, wait for other threads to finish, and point the reference to the original container to the new container.
CopyOnWrite containers are two different containers in the face of reading and writing, and the idea of separation of reading and writing is also used.
Thread unsafe solution of 2.HashSet
If it is new HashSet here, it is still possible to have the same concurrent modification exception as ArrayList above. The solution looks at the comments in the code.
Package test.notsafe; import java.util.Collections;import java.util.HashSet;import java.util.Set;import java.util.UUID;import java.util.concurrent.CopyOnWriteArraySet; / * demonstrate the thread unsafe problem of HashSet and its solution * / public class ThreadDemo3 {public static void main (String [] args) {/ / Set set = new HashSet () / / solution 1:Collections / / Set set = Collections.synchronizedSet (new HashSet ()); / / solution 2:CopyOnWriteArraySet Set set = new CopyOnWriteArraySet (); for (int I = 0; I
< 20; i++) { new Thread(() ->{set.add (UUID.randomUUID (). ToString (). Substring (0J8)); System.out.println (set);}, String.valueOf (I). Start ();}} 3.HashMap thread unsafe solution package test.notsafe; import java.util.Collections;import java.util.HashMap;import java.util.Map;import java.util.UUID;import java.util.concurrent.ConcurrentHashMap / * demonstrate HashMap thread unsafety problems and solutions * / public class ThreadDemo4 {public static void main (String [] args) {/ / Map map = new HashMap (); / / solution 1:Collections / / Map map = Collections.synchronizedMap (new HashMap ()); / / solution 2:ConcurrentHashMap Map map = new ConcurrentHashMap (); for (int I = 0; I
< 10; i++) { String key = String.valueOf(i); new Thread(() ->{map.put (key,UUID.randomUUID (). ToString (). Substring (0Pei8)); System.out.println (map);}, String.valueOf (I). Start ();} is all the contents of this article entitled "how to solve the unsafe problems of ArrayList, HashSet and HashMap in Java multithreading with high concurrency". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.