当前位置:网站首页>Atomicinteger class is used in multithreading to ensure thread safety
Atomicinteger class is used in multithreading to ensure thread safety
2022-07-22 17:14:00 【It's hard not to write code all day】
1 What is thread safety
Suppose our website needs to count the number of users , We need to achieve this through the self increment of variables :count++; This operation has thread safety problems :
The number of people counted at last is small ;
2 Problem analysis
count++ The operation of is divided into three steps :
Read count Value
Calculation count+1 Value
Save the new value into count
hypothesis count The value is 100, Two threads A and B All operations have been performed 1,
Then perform the operation at the same time 2,A Do it first 3, At this time count The value is 101,
B Perform the operation again 3, Before B The value read is 100, Finish the operation 3 after B
The result is still 101, So there is a problem with the data . Because of the above operation
It's not atomic , Can be executed separately .
3 solve
AtomicInteger The problem above has been solved , Use it to perform statistics :
static AtomicInteger at = new AtomicInteger(0);
public static void main(String[] args) {
for(int i = 0;i < 10000;i++){
new Thread(()->{
at.incrementAndGet();}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("count = " + at.get());
}
AtomicInteger There are keywords in the source code volatile;
It ensures that volatile Field updates inform other threads in a predictable way . In short volatile When a thread modifies a variable , Another thread can read the modified value .
4 summary
AtomicInteger It can realize the atomic operation of integer data , It can ensure data security in the environment of multithreading concurrency , And the optimistic lock is used internally , Higher concurrency performance than using lock mechanism ;
volatile It ensures that when a thread modifies data , Other threads can also see the modification of data
CAS Operation ensures the security of data modification
5 Thread count failed
Multiple threads execute a piece of logic , Count how many threads failed
ConcurrentMap<Integer, AtomicInteger> jobTimeoutCountMap = new ConcurrentHashMap<>();
// branch 10 Threads , Each thread is self increasing 2000 Time
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 2000; i++) {
AtomicInteger timeoutCount = jobTimeoutCountMap.putIfAbsent(22, new AtomicInteger(1));
if (timeoutCount != null) {
// Record the number of slow tasks
timeoutCount.incrementAndGet();
}
}
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(jobTimeoutCountMap.get(22));
边栏推荐
猜你喜欢
活动推荐| Apache Pulsar 在 vivo 的探索与实践 即将开播
Realization of a springboard machine
QT warning: c4819: this file contains characters that cannot be represented in the current code page (936). Please save the file in Unicode format to prevent data loss
[Topic sharing] open source topic of hande enterprise PAAS platform hzero
UE4 set collision body
数字化路径与实践思考
汉得企业级数字化PaaS平台 HZERO 1.9.0 版本正式发布!
5. SSH Remote Service
UE4 key to open the door
Hiam fine-grained unified authorization management helps enterprises achieve refined management and control of system permissions
随机推荐
In the arm64 environment, the third-party library hajimehoshi/oto of golang relies on the solution of alsa lib and CGO
汉得企业级PaaS平台 HZERO 发布 1.5.0.RELEASE 版本
工作流引擎在vivo营销自动化中的应用实践 | 引擎篇03
Anaconda download link
Make good use of these seven tips in code review, and it is easy to establish your opposition alliance
UE4 enters the designated area to realize the trigger acceleration function
July 19, 2022 daily
论文阅读【6】Autoaugment: Learning augmentation strategies from data
JSON_EXTRACT返回不正确问题
Activity recommendation | Apache pulsar's exploration and practice in vivo will be broadcast soon
tf.reduce_ sum()
Lepton 无损压缩原理及性能分析
Gd32f470 serial port idle interrupt +dma
Pytoch deep learning practice lesson 11 (CNN)
Are you still writing code for adding, deleting, modifying and checking? Direct one click generation
numpy.around
numpy.around
PyGame electronic warfare simulation effect
Use OpenCV to achieve the halo effect
Four main steps of web application penetration testing