Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve the thread unsafety of List

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What this article shares with you is about how to solve the thread unsafety of List. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Reasons for non-thread safety

Both ArrayList and LinkedList are thread-unsafe. Take the source code of ArrayList's add method as an example:

Public boolean add (E e) {ensureCapacityInternal (size+ 1); elementData [size++] = e; return true;}

Suppose thread An and thread B insert An and B into the List, respectively.

One is:

ElementData [size++] = e; this line of code is not an atomic operation, but the first step executed in two parts: elementdata [size] = e; second step: size++

Thread A performs the first step and inserts data An into the first location in the List, while the thread hangs.

Thread B performs the first step while size is still 0, so data B overwrites data A.

Thread A performs the second step to change size to 1; thread B performs the second step to make size 2.

Finally, the first location is data B, and the second location is null, which does not meet the expected results.

Second:

EnsureCapacityInternal (size + 1); this line of code may cause the default array size of ArrayIndexOutOfBoundsException ArrayList to be 10, if there are already nine elements in the array:

Thread An executes this code, verifies that there is no need for expansion, and the thread hangs.

Thread B executes this code, verifies that there is no need for expansion, and then places data B in the subscript 9, and the size becomes 10.

Thread A continues to execute, placing data An in the subscript 10, and ArrayIndexOutOfBoundsException will appear

Solutions to thread safety

Since both ArrayList and LinkedList are thread-unsafe, is there any way to solve the thread-safety problem?

Vector

A thread-safe class that modifies a method through the synchronize keyword.

Public synchronized void addElement (E obj) {modCount++; ensureCapacityHelper (elementCount+ 1); elementData [elementCount++] = obj;}

Collcetions.synchronizedList (new ArrayList ())

Using decorative mode, the generated collection adds mutex locks to the synchronous operation code block, which is thread-safe when the operation is performed. Note: this method does not synchronize when getting iterators and requires the user to synchronize manually.

Public void add (int index, E element) {synchronized (mutex) {list.add (index, element);}}

CopyOnWriteArrayList

JDK1.5 concurrent package provides a thread-safe variant of ArrayList, which achieves thread safety by acquiring object locks through ReentrantLock. CopyOnWriteArrayList reads and writes are separated, and copy a copy to operate when adding or deleting elements, while reading is unlocked, which ensures both the speed of reading and the thread safety of writing. Later, we will analyze the source code of the Java concurrency framework in detail.

Public E get (int index) {return get (getArray (), index);} public boolean add (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 ();}}

Note:

Due to the separation of read and write, CopyOnWriteArrayList may cause data consistency problems. Can not guarantee the real-time consistency of the data, can only ensure the final consistency of the data.

Due to the use of copy to manipulate data, there will be two arrays stationed in memory, which will occupy a large amount of memory.

The above is how to solve the thread unsafety of List. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please 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: 253

*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.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report