当前位置:网站首页>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.
边栏推荐
- In JS, string and array are converted to each other (I) -- the method of converting string into array
- 【mysql】触发器
- Introduction to the use of SAP Fiori application index tool and SAP Fiori tools
- JS according to the Chinese Alphabet (province) or according to the English alphabet - Za sort &az sort
- Replace Internet TV set-top box application through digital TV and broadband network
- JS操作dom元素(一)——获取DOM节点的六种方式
- 爱可可AI前沿推介(7.6)
- 2017 8th Blue Bridge Cup group a provincial tournament
- 14年本科毕业,转行软件测试,薪资13.5K
- 快讯:飞书玩家大会线上举行;微信支付推出“教培服务工具箱”
猜你喜欢

审稿人dis整个研究方向已经不仅仅是在审我的稿子了怎么办?

缓存更新策略概览(Caching Strategies Overview)

Dialogue with Jia Yangqing, vice president of Alibaba: pursuing a big model is not a bad thing

数据湖(八):Iceberg数据存储格式

KDD 2022 | 通过知识增强的提示学习实现统一的对话式推荐
![[MySQL] trigger](/img/b5/6df17eb254bbdb0aba422d08f13046.png)
[MySQL] trigger

The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop

Opencv learning example code 3.2.3 image binarization

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

3D face reconstruction: from basic knowledge to recognition / reconstruction methods!
随机推荐
袁小林:安全不只是标准,更是沃尔沃不变的信仰和追求
R语言做文本挖掘 Part4文本分类
LLVM之父Chris Lattner:为什么我们要重建AI基础设施软件
字符串的使用方法之startwith()-以XX开头、endsWith()-以XX结尾、trim()-删除两端空格
Aike AI frontier promotion (7.6)
启动嵌入式间:资源有限的系统启动
The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop
【Redis设计与实现】第一部分 :Redis数据结构和对象 总结
ICML 2022 | flowformer: task generic linear complexity transformer
OneNote in-depth evaluation: using resources, plug-ins, templates
What's the best way to get TFS to output each project to its own directory?
How do I remove duplicates from the list- How to remove duplicates from a list?
for循环中break与continue的区别——break-完全结束循环 & continue-终止本次循环
KDD 2022 | realize unified conversational recommendation through knowledge enhanced prompt learning
Web开发小妙招:巧用ThreadLocal规避层层传值
968 edit distance
R3live notes: image processing section
FZU 1686 龙之谜 重复覆盖
Set up a time server
Vim 基本配置和经常使用的命令