当前位置:网站首页>What happens if you have to use ArrayList in multithreading?
What happens if you have to use ArrayList in multithreading?
2022-07-29 02:26:00 【JavaMonsterr】
For the sake of understanding , At that time, only the code execution sequence was used to explain the cause of the exception . In fact, multithreading also involves Java Memory model , This article explains from this aspect .
Compare source
Let's take a look first Java 11 in , add What adjustments have been made to the method .
Java 8 in add Method implementation :
public boolean add(E e) {
ensureCapacityInternal(size + 1);
elementData[size++] = e;
return true;
}
Java 11 in add Method implementation :
public boolean add(E e) {
modCount++;
add(e, elementData, size);
return true;
}
private void add(E e, Object[] elementData, int s) {
if (s == elementData.length)
elementData = grow();
elementData[s] = e;
size = s + 1;
}The difference between the two sections of logic is whether the array subscript is determined :
elementData[size++] = e;,Java 8 You can usesizeLocate and assign , And then throughsize++Self increasingelementData[s] = e; size = s + 1;,Java 11 With the help of temporary variablessLocate and assign , And then throughsize = s + 1tosizeAssign new values to
Java 11 The advantage is , When assigning values to elements of an array , The subscript value is certain . in other words , Just enter add(E e, Object[] elementData, int s) In the method , Only the array elements at the specified position will be processed . also , size The value of is also based on s increase . Infer... In the order of execution , The final result may be lost , But there will be no null.( Multiple threads assign values to the same subscript , namely s equal , And in the end size Also equal .)
Check it out
Let's test it .
package com.kuaishou.is.datamart;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
CountDownLatch latch = new CountDownLatch(1);
CountDownLatch waiting = new CountDownLatch(3);
Thread t1 = new Thread(() -> {
try {
latch.await();
for (int i = 0; i < 1000; i++) {
list.add("1");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
waiting.countDown();
}
});
Thread t2 = new Thread(() -> {
try {
latch.await();
for (int i = 0; i < 1000; i++) {
list.add("2");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
waiting.countDown();
}
});
Thread t2 = new Thread(() -> {
try {
latch.await();
for (int i = 0; i < 1000; i++) {
list.add("2");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
waiting.countDown();
}
});
t1.start();
t2.start();
latch.countDown();
waiting.await();
System.out.println(list);
}
} stay Java 8 and Java 11 Respectively , Sure enough , There is ArrayIndexOutOfBoundsException and null The situation of . If not , That's the wrong posture , You need to try a few more times or more threads .
Think about it from another angle
The previous article explained the cause of the problem through the code execution sequence , Look again this time JMM Why .

As can be seen from the picture above ,Java A local memory area is created for each thread , in other words , Data used during code execution , Is the data cached locally by the thread . This cached data , It will exchange data with main memory ( Update the main memory data or update the data in this cache ).
Let's look at a sequence diagram to see why null( Array out of bounds exception, the same is true ):

From the sequence diagram, we can see that , In the process of execution , Two threads take size Values and elementData Array address , Most of them operate on their own local cache , After a period of execution , The data in the local cache will be written back to the main memory , Then it also reads the latest data from main memory and updates the local cache data . The exception occurred during this exchange .
This is the time , Some readers may think , Is it right? size and elementData Two variables plus volatile That's it . If you think so , Then you want to be simple . Thread safety is defined when the entire class is designed and implemented , In addition to attributes, you need to consider the impact of multithreading , Method ( The main method is to modify the attribute element ) Also need to consider .
ArrayList The positioning of is non thread safe , All of these methods do not consider locking shared resources under multithreading . Even if size and elementData Both variables are real-time read and write to main memory , however add and grow Method may also overwrite the data of another thread .
We from ArrayList Of add Method comments can tell , Method splitting is not for thread safety , But for execution efficiency and memory consumption :
This helper method split out from add(E) to keep method bytecode size under 35 (the -XX:MaxInlineSize default value), which helps when add(E) is called in a C1-compiled loop.
So , Use in multithreading scenarios ArrayList , The exception that should occur , None less .
边栏推荐
- Kubesphere-多节点安装
- Day 15 (VLAN related knowledge)
- 如何利用 RPA 实现自动化获客?
- Jetpack -- understand the use of ViewModel and livedata
- Vector similarity evaluation method
- What should I do if excel opens a CSV file containing Chinese characters and there is garbled code?
- 裂开了,一次连接池参数导致的雪崩问题
- 实验二:Arduino的三色灯实验
- awvs无法启动问题
- [RT learning note 1] RT thread peripheral routine - control LED light flashing
猜你喜欢

Data security and privacy computing summit - development and application of security intersection in privacy Computing: Learning

NPM install reports an error: eperm: operation not permitted, rename

即时通讯场景下安全合规的实践和经验

Jmeter之BeanShell生成MD5加密数据写入数据库
![[RT learning note 1] RT thread peripheral routine - control LED light flashing](/img/70/2c8cebd98948b5c92625c1a5423d97.png)
[RT learning note 1] RT thread peripheral routine - control LED light flashing

Excel 打开包含汉字的 csv 文件出现乱码该怎么办?

响应式织梦模板家装建材类网站

如果非要在多线程中使用 ArrayList 会发生什么?

Altium designer outputs Gerber and other production documents

Motionlayout -- realize animation in visual editor
随机推荐
Excel 用countif 统计
Experiment 2: Arduino's tricolor lamp experiment
开启TLS加密的Proftpd安全FTP服务器安装指南
如何把thinkphp5的项目迁移到阿里云函数计算来应对流量洪峰?
Realization of digital tube display based on C51
Excel 打开包含汉字的 csv 文件出现乱码该怎么办?
【上传图片2-可裁剪】
Three methods of STM32 delay function
"Activity recommendation" rush rush! 2022 international open source Festival has new content
结合Retrofit 改造OKHttp 缓存
记一次 ERROR scheduler.AsyncEventQueue: Dropping event from queue shared导致OOM
当Synchronized遇到这玩意儿,有个大坑,要注意
如何利用 RPA 实现自动化获客?
Summarize in the middle of the year | talk to yourself, live in the present, and count every step
What should I do if excel opens a CSV file containing Chinese characters and there is garbled code?
MySQL之数据查询(多表查询)
Quanzhi t3/a40i industrial core board, 4-core [email protected] The localization rate reaches 100%
Pointer - golden stage
Data query of MySQL (multi table query)
Interprocess communication - detailed explanation of the pipeline (explanation of graphic cases)