In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you the "List collection multithreading concurrency condition is not safe how to do", the content is easy to understand, clear, hope to help you solve the doubt, the following let the editor lead you to study and learn "List collection multithreading concurrency condition is not safe how to do" this article.
Preface
In the daily development process, List is our commonly used collection, such as querying the database content return value ratio will be loaded with a collection, but in the case of multi-thread concurrency, will there be security problems? Let's test how to solve if there is a security problem.
1. List collection uses simulation for concurrent testing
1.1 in single-threaded environment
Public static void main (String [] args) {/ / List collection List list = new ArrayList (); / / insert for in a loop (int I = 0; I
< 10; i++) { list.add(UUID.randomUUID().toString().substring(0,5)); System.out.println(list); }}You can see that under the condition of single thread, we have no problem with inserting list. Let's simulate what happens when we execute under the condition of concurrency.
1.2 in multithreaded environment
Public static void main (String [] args) {/ / List collection List list = new ArrayList (); / / insert for in a loop (int I = 0; I
< 10; i++) { // 开启线程执行 new Thread(()->{list.add (UUID.randomUUID (). ToString (). Substring (0P5)); System.out.println (list);}, "Thread List") .start ();}}
If ArrayList modifies it at the same time during iteration, it will throw a java.util.ConcurrentModificationException exception, which is a concurrent modification exception.
II. Solutions
2.1 using the Vector class
Public static void main (String [] args) {/ / List collection List list = new Vector (); / / insert for in a loop (int I = 0; I
< 10; i++) { // 开启线程执行 new Thread(()->{list.add (UUID.randomUUID (). ToString (). Substring (0P5)); System.out.println (list);}, "Thread List") .start ();}}
Vector is accessed synchronously, and its add method is decorated with the synchronized keyword at the bottom.
Test results:
2.1 use Collections.synchronizedList
Public static void main (String [] args) {/ / List collection List list = Collections.synchronizedList (new ArrayList ()); / / insert for in a loop (int I = 0; I
< 10; i++) { // 开启线程执行 new Thread(()->{list.add (UUID.randomUUID (). ToString (). Substring (0P5)); System.out.println (list);}, "Thread List") .start ();}}
Looking at the underlying source code, you can see that he also used the synchronized keyword modification.
2.3 using the concurrent container CopyOnWriteArrayList
Public static void main (String [] args) {/ / List collection List list = new CopyOnWriteArrayList (); / / insert for in a loop (int I = 0; I
< 10; i++) { // 开启线程执行 new Thread(()->{list.add (UUID.randomUUID (). ToString (). Substring (0P5)); System.out.println (list);}, "Thread List") .start ();}}
Look at the source code. It uses the lock locking mechanism.
Copy when writing, when there are multiple threads calling, copy a copy when writing, to avoid data problems caused by overwriting. Is not to modify the original collection when writing, but to make a new copy, after the modification, and then move the pointer.
Starting with JDK1.5, the Java concurrency package provides two concurrency containers implemented using the CopyOnWrite mechanism, which are CopyOnWriteArrayList and CopyOnWriteArraySet. The CopyOnWrite container is very useful and can be used in many concurrency scenarios.
Interpret the source code:
/ * Appends the specified element to the end of this list. * * @ param e element to be appended to this list * @ return {@ code true} (as specified by {@ link Collection#add}) * / public boolean add (E) {final ReentrantLock lock = this.lock;// reentrant lock lock.lock (); / / Lock try {Object [] elements = getArray (); int len = elements.length; Object [] newElements = Arrays.copyOf (elements, len + 1) / / copy the new array newElements [len] = e; setArray (newElements); / / point the reference to the new array return true;} finally {lock.unlock (); / / unlock}}
Add () adds a lock when adding a collection, ensuring synchronization and avoiding the need to Copy N copies when multithreading writes.
These are all the contents of this article entitled "what to do if it is not safe under the condition of List collection multithreading 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.