当前位置:网站首页>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 between webgl and webgpu [3] - vertex buffer
- Common static methods of math class
- Rasa 3.x 学习系列-Rasa X 社区版(免费版) 更改
- Data analysis - Thinking foreshadowing
- UVA11294-Wedding(2-SAT)
- C# Linq Demo
- YML configuration, binding and injection, verification, unit of bean
- When to use useImperativeHandle, useLayoutEffect, and useDebugValue
- Summary of binary tree recursive routines
- Mathematical formula screenshot recognition artifact mathpix unlimited use tutorial
猜你喜欢

GFS distributed file system

成为程序员的你,后悔了吗?

Data analysis - Thinking foreshadowing

21.PWM应用编程

Spreadjs 15.1 CN and spreadjs 15.1 en

Rsync remote synchronization

STM32__06—单通道ADC

5. Logistic regression

GFS分布式文件系统

Spécifications techniques et lignes directrices pour la sélection des tubes TVS et ESD - Recommandation de jialichuang
随机推荐
Rsync remote synchronization
如何获取localStorage中存储的所有值
C# 文件与文件夹操作
C# Linq Demo
Cwaitabletimer timer, used to create timer object access
【LeetCode】5. Valid Palindrome·有效回文
AsyncSocket长连接棒包装问题解决
poj 2762 Going from u to v or from v to u? (推断它是否是一个薄弱环节图)
【LeetCode】5. Valid palindrome
98. Verify the binary search tree ●●
There are 14 God note taking methods. Just choose one move to improve your learning and work efficiency by 100 times!
5. Logistic regression
idea 连接mysql ,直接贴配置文件的url 比较方便
Krypton Factor purple book chapter 7 violent solution
698. 划分为k个相等的子集 ●●
Introduction to JVM
How to design API return code (error code)?
进击的技术er——自动化
(4) UART application design and simulation verification 2 - RX module design (stateless machine)
From the perspective of quantitative genetics, why do you get the bride price when you get married