当前位置:网站首页>Principle of copyonwritearraylist copy on write
Principle of copyonwritearraylist copy on write
2022-06-11 05:53:00 【Endwas】
CopyOnWriteArrayList It is a kind of copy on write ArrayList, And is a thread safe version . There are many data structures of similar design , Such as CopyOnWriteArraySet.
If you want to understand the specific principle analysis , Look at chapter two principle , Why copy ?
expand :CopyOnWriteArraySet
Thread safe set, Bottom use CopyOnWriteArrayList
add Called when addIfAbsent To guarantee There is no repetition of elements
And in general set Different , image hashset、treeset The bottom layer is the corresponding call map To operate
1. brief introduction
CopyOnWriteArrayList As the name suggests, copy list on write , Avoid direct read-write mutex locking , Poor performance .
read : Direct read without lock .
Write : Copy a , To operate . Multiple write operations Lock Mutual exclusion ensures data security .
Advantages and disadvantages :
advantage : Reduce read lock , Improve code performance , At the same time, ensure thread safety .
shortcoming :
- When the internal data is large , Copying requires a lot of memory overhead , May lead to OOM Happen .
- Only the final consistency of data can be guaranteed .
The final consistency is discussed in three cases :
public boolean add(E e) {
synchronized(this.lock) {
Object[] es = this.getArray();
int len = es.length;
es = Arrays.copyOf(es, len + 1);
// 1️⃣
es[len] = e;
// 2️⃣
this.setArray(es);
// 3️⃣
return true;
}
}
1️⃣ Data not modified
At this time, read the old data
2️⃣ Modifying data , But the reference is not pointed to the new array
At this time, the old data will also be read .
3️⃣ Modifying data , Point the reference to the new data
At this time, the latest data can be read .
2. principle
First ask a question
Why copy on write , Can't you modify the original array directly ?
After all, they are locked when writing , There are no multiple threads modifying at the same time , It also saves the memory cost of copying and modifying data 、 Consistency problems when pointing to new arrays .
I have thought about this problem for a long time . What is the purpose of a write time copy , Why do this ?
To solve this problem , The key is to understand volatile Keyword
volatile There are two things about it
- Thread visibility
- Avoid reordering instructions
Here is a brief introduction to visibility , Multiple CPU There will be internal cache to improve the reading efficiency , First read from memory to cache , without volatile Keyword , Other threads have modified the value of this property , Brush back memory , But the current thread is not aware of the changes , Still reading old cache values , The problem of inconsistent data . So add volatile Change can be felt . At the same time, the key point is that only Citation modification Will be perceived , Such as object modification 、 Array object reference modification , Variable modification, etc .
// volatile Embellished
private transient volatile Object[] array;
As mentioned earlier, this is an array reference type , So if you simply modify elements in the original array, it cannot be perceived by other threads , That's why it's used here Copy To modify the reference point in time “ notice ” Other thread data changes .
That's why a write - time copy method is used , Data security .
3. And ReadWriteLock Compare
Read-write lock : Can't read while writing , You can't write while reading , So and CopyOnWrite It's different
| Read-write lock | read | Write |
|---|---|---|
| read | √ | × |
| Write | × | × |
4. summary
CopyOnWriteArrayList Very clever use of volatile Keywords to ensure thread read and write security , Although it avoids the low performance scenario of locking while reading and writing , But it also takes up extra memory , Data can not guarantee strong consistency and other shortcomings , You need to use... According to the scene , Suitable for reading more and writing less .
边栏推荐
- Getbackgroundaudiomanager controls music playback (dynamic binding of class name)
- 安装Oracle数据库
- Yoyov5's tricks | [trick8] image sampling strategy -- Sampling by the weight of each category of the dataset
- Configure the rust compilation environment
- JS -- reference type
- Reading the registry using batch
- Gilde failed to go to the listener to call back the reason record when loading the Gaussian blur image
- Share an RSA encryption and decryption tool class, including public key encryption, private key decryption, private key encryption, public key decryption, private key signature, public key verificatio
- Convert result set of SQL to set
- Wechat applet text built-in component newline character does not newline reason
猜你喜欢

NDK learning notes (XI) POSIX sockect local communication

NDK learning notes (I)

If the MAC fails to connect with MySQL, it will start and report an error

Deep learning distributed training

20多种云协作功能,3分钟聊透企业的数据安全经

那个酷爱写代码的少年后来怎么样了——走近华为云“瑶光少年”

跨境电商测评自养号团队应该怎么做?

Pycharm usage experience

Getting started with kotlin

NDK R21 compiles ffmpeg 4.2.2+x264 and converts video files using ffmpeg
随机推荐
The meaning in the status column displayed by PS aux command
Preliminary understanding of multi task learning
[go deep into kotlin] - flow advanced
微信小程序text内置组件换行符不换行的原因-wxs处理换行符,正则加段首空格
修复Yum依赖冲突
Slide the receleview horizontally to the far right to listen to the page loading function
Multithreading tutorial (XXII) happens before principle
Sword finger offer 50: the first character that appears only once
Convert result set of SQL to set
NDK learning notes (13) create an avi video player using avilib+opengl es 2.0
使用Batch设置IP地址
NLP-D46-nlp比赛D15
SwiftUI: Navigation all know
OJDBC在Linux系统下Connection速度慢解决方案
NDK learning notes (I)
配置Rust编译环境
Qmake implementation of QT project Pro script to vs solution
Elk log system practice (V): install vector and output data to es and Clickhouse cases
【深入kotlin】 - Flow 进阶
ImageView supporting single finger sliding and double finger scaling