当前位置:网站首页>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.
边栏推荐
- 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
- After working for 5 years, this experience is left when you reach P7. You have helped your friends get 10 offers
- The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop
- [Li Kou brush questions] 32 Longest valid bracket
- 防火墙基础之外网服务器区部署和双机热备
- js 根据汉字首字母排序(省份排序) 或 根据英文首字母排序——za排序 & az排序
- Swagger UI tutorial API document artifact
- Is it profitable to host an Olympic Games?
- Dialogue with Jia Yangqing, vice president of Alibaba: pursuing a big model is not a bad thing
- 愛可可AI前沿推介(7.6)
猜你喜欢
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
3D人脸重建:从基础知识到识别/重建方法!
Caching strategies overview
Swagger UI tutorial API document artifact
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
Opencv learning example code 3.2.3 image binarization
Four common ways and performance comparison of ArrayList de duplication (jmh performance analysis)
ICML 2022 | flowformer: task generic linear complexity transformer
OneNote in-depth evaluation: using resources, plug-ins, templates
[MySQL] trigger
随机推荐
【深度学习】PyTorch 1.12发布,正式支持苹果M1芯片GPU加速,修复众多Bug
[MySQL] trigger
【滑动窗口】第九届蓝桥杯省赛B组:日志统计
Web开发小妙招:巧用ThreadLocal规避层层传值
string的底层实现
MLP (multilayer perceptron neural network) is a multilayer fully connected neural network model.
[go][转载]vscode配置完go跑个helloworld例子
[redis design and implementation] part I: summary of redis data structure and objects
Opencv learning example code 3.2.3 image binarization
OSPF多区域配置
Pat 1078 hashing (25 points) ⼆ times ⽅ exploration method
The most comprehensive new database in the whole network, multidimensional table platform inventory note, flowus, airtable, seatable, Vig table Vika, flying Book Multidimensional table, heipayun, Zhix
跨分片方案 总结
Set up a time server
The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop
启动嵌入式间:资源有限的系统启动
KDD 2022 | realize unified conversational recommendation through knowledge enhanced prompt learning
愛可可AI前沿推介(7.6)
Quick news: the flybook players' conference is held online; Wechat payment launched "education and training service toolbox"
Chris LATTNER, the father of llvm: why should we rebuild AI infrastructure software