当前位置:网站首页>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;
}
}
边栏推荐
- Comparison of parameters between TVs tube and zener diode
- 同事悄悄告诉我,飞书通知还能这样玩
- Attacking technology Er - Automation
- From the perspective of quantitative genetics, why do you get the bride price when you get married
- Introduction to JVM
- UART Application Design and Simulation Verification 2 - TX Module Design (Stateless machine)
- Fiddler Everywhere 3.2.1 Crack
- AsyncSocket长连接棒包装问题解决
- 20.移植Freetype字体库
- Bao Yan notes II software engineering and calculation volume II (Chapter 13-16)
猜你喜欢
Brushless drive design -- on MOS drive circuit
Research notes I software engineering and calculation volume II (Chapter 1-7)
保研笔记二 软件工程与计算卷二(13-16章)
Bao Yan notebook IV software engineering and calculation volume II (Chapter 8-12)
2: Chapter 1: understanding JVM specification 1: introduction to JVM;
STM32__ 06 - single channel ADC
芯源&立创EDA训练营——无刷电机驱动
Data analysis - Thinking foreshadowing
TVS管和ESD管的技術指標和選型指南-嘉立創推薦
Development specification: interface unified return value format [resend]
随机推荐
rsync远程同步
MySQL delete uniqueness constraint unique
Live tiktok shop 2022 latest gameplay card slot overseas live e-commerce new traffic
grafana工具界面显示报错influxDB Error
STM32__ 06 - single channel ADC
UVA – 11637 Garbage Remembering Exam (组合+可能性)
Leetcode sword finger offer brush questions - day 21
Neural structured learning - Part 3: training with synthesized graphs
Calculating the number of daffodils in C language
Why use weak pointers for delegation- Why use weak pointer for delegation?
Creative mode 1 - single case mode
VS2010 writes DLL and unit test of dynamic link library, and transfers the correctness of DLL test
Dynamic memory management (malloc/calloc/realloc)
Scala concurrent programming (II) akka
(4)UART应用设计及仿真验证2 —— RX模块设计(无状态机)
Russian Foreign Ministry: Japan and South Korea's participation in the NATO summit affects security and stability in Asia
Go language implementation principle -- map implementation principle
C# 反射与Type
AsyncSocket长连接棒包装问题解决
In C#, why can't I modify the member of a value type instance in a foreach loop?