当前位置:网站首页>Use CAS instead of synchronized
Use CAS instead of synchronized
2022-07-05 23:39:00 【Archie_ java】
It needs to be often used in development synchronized Guarantee code Thread safety , Waiting resources will be blocked under competitive conditions , If you are allowed to compete for less than resources, return failure , You can use cas Reduce blocking time . Let's have a look at cas Single instance mode of .
public class NonBlock {
private static volatile NonBlock nonBlock;
private static AtomicBoolean atomicBoolean = new AtomicBoolean(false);
public static NonBlock getInstance() {
if (nonBlock == null) {
if (atomicBoolean.compareAndSet(false, true)) {
nonBlock = new NonBlock();
}
}
return nonBlock;
}
}
In this singleton mode , differ synchronized The block , Multi-threaded environment ,getInstance Ensure that only one object will be created , Possible return nonBlock Is an empty object . but , If it is allowed to return an empty object ,
public class RedPacket {
private long balance;
private int num;
public RedPacket(long balance, int num) {
this.balance = balance;
this.num = num;
}
public long get() {
if (balance < 1 || num < 1) {
return -1;
}
if (num == 1) {
long result = balance;
balance = 0;
num--;
return result;
}
long average = balance / num;
long result = ThreadLocalRandom.current().nextLong(1, average * 2);
balance -= result;
num--;
return result;
}
We can also use cas Achieve the purpose of non blocking , This ensures thread safety , When there is competition, it indicates that the competition has failed , The exact point is to prompt that the balance may be greater than 0, Coming first may not be able to grab , Later, people can rob .
public class RedPacket {
private long balance;
private AtomicInteger num;
public RedPacket(long balance, int num) {
this.balance = balance;
this.num = new AtomicInteger(num);
}
public long get() {
int number = num.get();
long balan = balance;
if (balan < 1 || number < 1) {
return -1;
}
if (num.compareAndSet(number, number - 1)) {
if (number - 1 == 0) {
balance = 0;
return balan;
}
long average = balan / number;
long result = ThreadLocalRandom.current().nextLong(1, average * 2);
balance -= result;
}
return -1;
}
}
边栏推荐
- What is the process of building a website
- Brushless drive design -- on MOS drive circuit
- golang代码检查工具
- Technical specifications and model selection guidelines for TVs tubes and ESD tubes - recommended by jialichuang
- From the perspective of quantitative genetics, why do you get the bride price when you get married
- MySQL replace primary key delete primary key add primary key
- C# Linq Demo
- When to use useImperativeHandle, useLayoutEffect, and useDebugValue
- Fiddler Everywhere 3.2.1 Crack
- [classical control theory] summary of automatic control experiment
猜你喜欢
STM32__06—单通道ADC
Neural structured learning - Part 2: training with natural graphs
Go language implementation principle -- lock implementation principle
GFS分布式文件系統
There are 14 God note taking methods. Just choose one move to improve your learning and work efficiency by 100 times!
TVS管和ESD管的技術指標和選型指南-嘉立創推薦
Research notes I software engineering and calculation volume II (Chapter 1-7)
Go language introduction detailed tutorial (I): go language in the era
Hcip course notes-16 VLAN, three-tier architecture, MPLS virtual private line configuration
Bao Yan notebook IV software engineering and calculation volume II (Chapter 8-12)
随机推荐
Hcip course notes-16 VLAN, three-tier architecture, MPLS virtual private line configuration
ts类型声明declare
保研笔记二 软件工程与计算卷二(13-16章)
el-cascader的使用以及报错解决
Objective C message dispatch mechanism
Fiddler Everywhere 3.2.1 Crack
MySQL (1) -- related concepts, SQL classification, and simple operations
VS2010编写动态链接库DLL和单元测试,转让DLL测试的正确性
Pyqt control part (I)
(4)UART應用設計及仿真驗證2 —— TX模塊設計(無狀態機)
Dynamic memory management (malloc/calloc/realloc)
UART Application Design and Simulation Verification 2 - TX Module Design (Stateless machine)
Rasa 3.x 学习系列-Rasa 3.2.1 新版本发布
做自媒体影视短视频剪辑号,在哪儿下载素材?
asp. Net pop-up layer instance
Go language introduction detailed tutorial (I): go language in the era
Idea connects to MySQL, and it is convenient to paste the URL of the configuration file directly
AsyncSocket长连接棒包装问题解决
(4) UART application design and simulation verification 2 - RX module design (stateless machine)
4 points tell you the advantages of the combination of real-time chat and chat robots