当前位置:网站首页>Multithreading tutorial (XXIII) thread safety without lock
Multithreading tutorial (XXIII) thread safety without lock
2022-06-11 05:29:00 【Have you become a great God today】
Multithreading tutorial ( 23 ) Realize thread safety without lock
Title Description :
Total 10000 element ,1000 Personal withdrawal , Per person 10 block , The balance after withdrawal is just 0.
Lock method
class AccountUnsafe implements Account {
private Integer balance;
public AccountUnsafe(Integer balance) {
this.balance = balance;
}
@Override
public synchronized Integer getBalance() {
return balance;
}
@Override
public synchronized void withdraw(Integer amount) {
balance -= amount;
}
}
The result is :
0 cost: 399 ms
Lock free solutions
class AccountSafe implements Account {
private AtomicInteger balance;
public AccountSafe(Integer balance) {
this.balance = new AtomicInteger(balance);
}
@Override
public Integer getBalance() {
return balance.get();
}
@Override
public void withdraw(Integer amount) {
while (true) {
int prev = balance.get();
int next = prev - amount;
if (balance.compareAndSet(prev, next)) {
break;
}
}
// It can be simplified to the following method
// balance.addAndGet(-1 * amount);
}
}
Execute test code
public static void main(String[] args) {
Account.demo(new AccountSafe(10000));
}
The result of a certain execution
0 cost: 302 ms
In fact, the lock free solution is to use cas, Compare the internal variables of the thread with the variables of the main thread before assigning values , Assign values at the same time , Avoid the use of locks
However, this scheme is suitable for a small number of threads , Because there are too many threads cas Will never succeed , Reduce performance .
边栏推荐
- Retinanet+keras train their own data set to tread on the pit
- lower_ Personal understanding of bound function
- 深度学习分布式训练
- Share | defend against physically realizable image classification attacks
- Traversal of binary tree -- restoring binary tree by two different Traversals
- Customize the layout of view Foundation
- Overview of self attention acceleration methods: Issa, CCNET, cgnl, linformer
- Cascade EF gan: local focus progressive facial expression editing
- Share | guide language image pre training to achieve unified visual language understanding and generation
- Intercept file extension
猜你喜欢

Preliminary understanding of multi task learning

(十五)红外通信

Big meal count (time complexity) -- leetcode daily question

Number of atoms (easy to understand)

PCB走线到底能承载多大电流

Deep search + backtracking

BERT知识蒸馏

Wechat applet uploads the data obtained from database 1 to database 2

Why is the smart door lock so popular? What about the smart door locks of MI family and zhiting?

袋鼠云数栈基于CBO在Spark SQL优化上的探索
随机推荐
PCB走線到底能承載多大電流
自定义View基础之Layout
2021-04-19
[entry level basics] node basic knowledge summary
在未来,机器人或 AI 还有多久才能具备人类的创造力?
Wechat applet, automatic line feed for purchasing commodity attributes, fixed number of divs, automatic line feed for excess parts
27. Remove elements
Es IK installation error
IOU series (IOU, giou, Diou, CIO)
lower_ Personal understanding of bound function
2021 iccv paper sharing - occlusion boundary detection
AAAI2022-ShiftVIT: When Shift Operation Meets Vision Transformer
Introduction to coordinate system in navigation system
The programmers of a large factory after 95 were dissatisfied with the department leaders, and were sentenced for deleting the database and running away
Recherche sur l'optimisation de Spark SQL basée sur CBO pour kangourou Cloud Stack
Number of atoms (easy to understand)
JVM tuning 6: GC log analysis and constant pool explanation
[go deep into kotlin] - flow advanced
袋鼠雲數棧基於CBO在Spark SQL優化上的探索
【入门级基础】Node基础知识总结