当前位置:网站首页>Comparison between multithreaded CAS and synchronized
Comparison between multithreaded CAS and synchronized
2022-07-06 21:21:00 【Archie_ java】
Business scenario : You need to implement a counting function that supports concurrency
1、 The basic realization of counting function is :
public class Increment{
private int count = 0;
public void add(){
count++;
}
}
2、 The above implementation is not safe in a concurrent environment , Therefore, modify the scheme 1 It's locking synchronized:
public class Increment{
private int count = 0;
public synchronized void add(){
count++;
}
}
// Pessimistic locking , After locking, there can only be one thread for you to execute ++ operation , Other threads need to wait
// There will be no count The problem of inaccurate counting , Thread safety
3、 But the above implementation , Will serialize threads , Queue for lock 、 Lock 、 Processing data 、 Release the lock , And sending it seems unreasonable
Revise the plan 2 It's using Java Contract issuance concurrent Under the Atomic Atomic classes
public class Increment{
private AtomicInteger count = new AtomicInteger();
public synchronized void add(){
count.incrementAndGet();
}
}
// Multiple threads can execute concurrently AtomicInteger Of incrementAndGet() Method , hold count The sum of the values of 1 And return the latest value after accumulation
//Atomic The bottom layer of atomic class is unlocked CAS Mechanism , Ensure the safety of multi-threaded modification of a value
4、 Realization principle :
(1) Each thread gets the current value first , And then one atom CAS operation , That's what atoms mean CAS The operation must be completed by itself , No interruptions ;
(2) stay CAS In operation , Compare the , The current value is the same as the value I just obtained , Whether it is equal or not , Yes means that no one has changed this value , Then set it to accumulate 1 The next value is ;
(3) Empathy , If someone is executing CAS when , Find that the value you obtained before is different from the current value , It means that someone else has modified the value , Lead to CAS Failure , After failure, enter a cycle , Get the value again , Re execution CAS operation .
5、CAS The problem of :
Every time I compare , Found that the value was changed by others , Will enter the infinite repetition cycle . When a large number of threads are highly concurrent, it is equivalent to an empty loop , Self rotation , Performance and efficiency are not particularly good .
Java8 A new class of LongAdder, Try using segmentation CAS And the way of automatic segmented migration to improve the high concurrency of multithreading CAS Performance of operation . The core idea is the separation of hot spots , similar concurrentHashMap.
边栏推荐
- FZU 1686 龙之谜 重复覆盖
- js中,字符串和数组互转(二)——数组转为字符串的方法
- Interviewer: what is the internal implementation of ordered collection in redis?
- Absolute primes (C language)
- JS学习笔记-OO创建怀疑的对象
- Thinking about agile development
- LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
- What's the best way to get TFS to output each project to its own directory?
- In JS, string and array are converted to each other (I) -- the method of converting string into array
- [go][转载]vscode配置完go跑个helloworld例子
猜你喜欢

Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software

嵌入式开发的7大原罪

Study notes of grain Mall - phase I: Project Introduction

每个程序员必须掌握的常用英语词汇(建议收藏)
![[Li Kou brush questions] 32 Longest valid bracket](/img/51/1ce4f9e8517dba214ec82b6567c923.png)
[Li Kou brush questions] 32 Longest valid bracket

防火墙基础之外网服务器区部署和双机热备

ICML 2022 | Flowformer: 任务通用的线性复杂度Transformer

968 edit distance

Deployment of external server area and dual machine hot standby of firewall Foundation

【论文解读】用于白内障分级/分类的机器学习技术
随机推荐
R language visualizes the relationship between more than two classification (category) variables, uses mosaic function in VCD package to create mosaic plots, and visualizes the relationship between tw
Divide candy
数据湖(八):Iceberg数据存储格式
@GetMapping、@PostMapping 和 @RequestMapping详细区别附实战代码(全)
This year, Jianzhi Tencent
跨分片方案 总结
启动嵌入式间:资源有限的系统启动
嵌入式开发的7大原罪
[Li Kou brush questions] 32 Longest valid bracket
快讯:飞书玩家大会线上举行;微信支付推出“教培服务工具箱”
The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends
Binary tree node at the longest distance
Mtcnn face detection
基于深度学习的参考帧生成
【滑动窗口】第九届蓝桥杯省赛B组:日志统计
2022 fields Award Announced! The first Korean Xu Long'er was on the list, and four post-80s women won the prize. Ukrainian female mathematicians became the only two women to win the prize in history
【力扣刷题】32. 最长有效括号
[redis design and implementation] part I: summary of redis data structure and objects
Nodejs tutorial let's create your first expressjs application with typescript
Aike AI frontier promotion (7.6)