当前位置:网站首页>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.
边栏推荐
- js中,字符串和数组互转(一)——字符串转为数组的方法
- SAP UI5 框架的 manifest.json
- [redis design and implementation] part I: summary of redis data structure and objects
- Summary of cross partition scheme
- Nodejs教程之让我们用 typescript 创建你的第一个 expressjs 应用程序
- 14年本科毕业,转行软件测试,薪资13.5K
- 愛可可AI前沿推介(7.6)
- This year, Jianzhi Tencent
- PHP saves session data to MySQL database
- Ravendb starts -- document metadata
猜你喜欢

3D人脸重建:从基础知识到识别/重建方法!
Why does MySQL index fail? When do I use indexes?

Interviewer: what is the internal implementation of ordered collection in redis?

Swagger UI tutorial API document artifact

监控界的最强王者,没有之一!

Aiko ai Frontier promotion (7.6)

039. (2.8) thoughts in the ward

ICML 2022 | flowformer: task generic linear complexity transformer

KDD 2022 | realize unified conversational recommendation through knowledge enhanced prompt learning
![[redis design and implementation] part I: summary of redis data structure and objects](/img/2e/b147aa1e23757519a5d049c88113fe.png)
[redis design and implementation] part I: summary of redis data structure and objects
随机推荐
966 minimum path sum
R语言做文本挖掘 Part4文本分类
@PathVariable
How do I remove duplicates from the list- How to remove duplicates from a list?
Select data Column subset in table R [duplicate] - select subset of columns in data table R [duplicate]
在最长的距离二叉树结点
Forward maximum matching method
R3live notes: image processing section
HMS Core 机器学习服务打造同传翻译新“声”态,AI让国际交流更顺畅
Swagger UI教程 API 文档神器
【mysql】触发器
SAP Fiori应用索引大全工具和 SAP Fiori Tools 的使用介绍
20220211 failure - maximum amount of data supported by mongodb
[interpretation of the paper] machine learning technology for Cataract Classification / classification
ICML 2022 | flowformer: task generic linear complexity transformer
2017 8th Blue Bridge Cup group a provincial tournament
【滑动窗口】第九届蓝桥杯省赛B组:日志统计
@GetMapping、@PostMapping 和 @RequestMapping详细区别附实战代码(全)
Common English vocabulary that every programmer must master (recommended Collection)
The use method of string is startwith () - start with XX, endswith () - end with XX, trim () - delete spaces at both ends