当前位置:网站首页>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 usesize
Locate and assign , And then throughsize++
Self increasingelementData[s] = e; size = s + 1;
,Java 11 With the help of temporary variabless
Locate and assign , And then throughsize = s + 1
tosize
Assign 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 .
边栏推荐
- 年中总结 | 与自己对话,活在当下,每走一步都算数
- Detailed explanation of IVX low code platform series -- Overview (II)
- 第3章业务功能开发(线索备注的删除和修改)
- 响应式织梦模板装修设计类网站
- On Multithreading
- C language improvement (I)
- “两个披萨”团队的分支管理实践
- Even PostgreSQL problem: expected authentication request from server, but received V
- DevOps 团队如何抵御 API 攻击?
- What is scope and scope chain
猜你喜欢
Responsive dream weaving template outdoor camping website
Esbuild Bundler HMR
会议OA之会议通知
Data security and privacy computing summit - development and application of security intersection in privacy Computing: Learning
Custom MVC principle and framework implementation
DevOps 团队如何抵御 API 攻击?
聊聊接口性能优化的11个小技巧
What is scope and scope chain
基于对象的实时空间音频渲染丨Dev for Dev 专栏
Problems encountered in special flow & properties property set instances and Solutions
随机推荐
ES6 syntax extension
Prometheus + AlertManager 消息预警
Eight practical new functions of es2022
Website Collection
密码安全如何保障?安全浏览器如何管理密码?
Control buzzer based on C51
Idea connection database
12. < tag dynamic programming and subsequence, subarray> lt.72. edit distance
Click the button to slide to the specified position
特殊流&Properties属性集实例遇到的问题及解决方法
Problems encountered in special flow & properties property set instances and Solutions
Excel uses countif statistics
Jetpack -- understand the use of ViewModel and livedata
多边形点测试
NPM install reports an error: eperm: operation not permitted, rename
Explain the four asynchronous solutions of JS in detail: callback function, promise, generator, async/await
快速掌握Nodejs安装以及入门
awvs无法启动问题
“12306”的架构到底有多牛逼?
Resnet50 + k-fold cross validation + data enhancement + drawing (accuracy, recall, F value)