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 understand CopyOnWriteArrayList under JUC in Java

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to understand CopyOnWriteArrayList under JUC in Java". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to understand CopyOnWriteArrayList under JUC in Java".

ArrayList is one of our common utility classes, but in the case of multithreading, ArrayList as a shared variable is not thread-safe. There are two main reasons:

1. ArrayList's own elementData, size and modCount are not locked during the operation.

2. These variables are not modified by volatile. In the case of multithreading, the value may be overwritten when operating on these variables.

What if we want to use ArrayList in the case of multithreading? There are several ways to do this:

Use Collections.SynchronizedList

Use CopyOnWriteArrayList under JUC

First, let's take a look at SynchronizedLis,Collections, which is actually a locking package for ArrayList, which can be seen from the source code.

... Part of the source code, complete source code, please check the JDK source code.

Public void add (int index, E element) {

Synchronized (mutex) {list.add (index, element);}

}

Public E remove (int index) {

Synchronized (mutex) {return list.remove (index);}

}

It is relatively simple for Collections.SynchronizedList, that is, it is locked and packaged, so there is no need to say much.

CopyOnWriteArrayList is also a concurrent container class under JUC. I don't know if you have found it, but all the collection classes you use can basically find a concurrent class under JUC, for example, hashMap has a corresponding ConcurrentHashMap.

There is no difference in the overall architecture between CopyOnWriteArrayList and ArrayList, and the underlying implementation is based on arrays. There are probably two differences:

The underlying array is modified by the volatile keyword

Lock when data changes are made to the array

The locking operation of CopyOnWriteArrayList is not the same as the simple locking of Collections.SynchronizedList, and the locking process in CopyOnWriteArrayList is worth learning. The locking process of CopyOnWriteArrayList can be summarized into the following four steps:

1. Add lock

2. Copy the new array from the original array

3. Operate on the new array and assign the new array to the array container

4. Unlock

To gain an in-depth understanding of the concurrency implementation of CopyOnWriteArrayList by combining the source code, we choose ArrayList's simplest operation to add elements to the end of the array to analyze the implementation process. The source code is as follows:

/ * *

* 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 e) {

/ / acquire the lock. Note that this is a global lock.

Final ReentrantLock lock = this.lock

/ / locking operation

Lock.lock ()

Try {

/ / get the array

Object [] elements = getArray ()

Int len = elements.length

/ / copy the contents of the array to the new array

Object [] newElements = Arrays.copyOf (elements, len + 1)

/ / A pair of new array operations

NewElements [len] = e

/ / change the reference of the underlying array

SetArray (newElements)

Return true

} finally {

/ / unlock

Lock.unlock ()

}

}

CopyOnWriteArrayList achieves container security by locking. You may wonder why a new array is introduced. The copy of the array is still time-consuming. Why not just operate on the original array? The main reasons are as follows:

The volatile keyword modifies the array. If we simply change the values of some of the elements on the original array, we can't trigger the visibility. We have to change the memory address of the array, that is, we have to reassign the array.

Copying on the new array does not have any effect on the old array, and can only be accessed externally after the complete copy of the new array, reducing the impact of data changes in the old array during the assignment process. Such as the classic ConcurrentModificationException exception problem.

Other new methods to check the source code, the difference is not much, basically the same. Deleting an array is similar to adding it, except that when you delete it, you will have a different selection strategy when assigning a value to a new array. I posted the source code:

Public E remove (int index) {

Final ReentrantLock lock = this.lock

/ / add lock

Lock.lock ()

Try {

Object [] elements = getArray ()

Int len = elements.length

E oldValue = get (elements, index)

/ / figure out the problem to be moved first

Int numMoved = len-index-1

/ / Select a policy based on the location of the move

If (numMoved = = 0)

SetArray (Arrays.copyOf (elements, len-1))

Else {

Object [] newElements = new Object [len-1]

System.arraycopy (elements, 0, newElements, 0, index)

System.arraycopy (elements, index + 1, newElements, index

NumMoved)

SetArray (newElements)

}

Return oldValue

} finally {

/ / unlock

Lock.unlock ()

}

}

Thank you for your reading, the above is the content of "how to understand CopyOnWriteArrayList under JUC in Java". After the study of this article, I believe you have a deeper understanding of how to understand CopyOnWriteArrayList under JUC in Java. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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.

Share To

Development

Wechat

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

12
Report