当前位置:网站首页>CAS operation
CAS operation
2022-07-25 07:58:00 【The season when the monsoon dies】
What is? CAS
if (value == expectedValue) {
value = newValue;
}public final native boolean compareAndSwapObject(Object o, long offset, Object expected, Object x);
public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x);
public final native boolean compareAndSwapLong(Object o, long offset, long expected, long x);public class UnsafeFactory {
/**
* obtain Unsafe object * @return
*/
public static Unsafe getUnsafe() {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
return (Unsafe) field.get(null);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get the memory offset of the field
* @param unsafe
* @param clazz
* @param fieldName
* @return
*/
public static long getFieldOffset(Unsafe unsafe, Class clazz, String fieldNam e) {
try {
return unsafe.objectFieldOffset(clazz.getDeclaredField(fieldName));
} catch (NoSuchFieldException e) {
throw new Error(e);
}
}
}
CAS The essence is one CPU Atomic instructions for , Guaranteed by operating system hardware . Different operating systems and different CPU It will be different Realization .
CAS stay Java Application in language
stay Java In programming, we usually don't directly use CAS, It's all through JDK Encapsulated concurrency tool classes for indirect use , These concurrency tool classes are java.util.concurrent In bag .
J.U.C yes
java.util.concurrentFor short , That's what people say Java Concurrent programming toolkit , Interviews often test , Very, very important .
- Basic types :AtomicInteger、AtomicLong、AtomicBoolean;
- Reference type :AtomicReference、AtomicStampedRerence、AtomicMarkableReference;
- An array type :AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray
- Object attribute atomic modifier :AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater
- Atomic type accumulator (jdk1.8 Added class ):DoubleAccumulator、DoubleAdder、 LongAccumulator、LongAdder、Striped64
// Add the original value in the instance by atom 1, It returns the old value before auto increment ;
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
//getAndSet(int newValue): Update the value in the instance to the new value , And return the old value ; 、
public final boolean getAndSet(boolean newValue) {
boolean prev;
do {
prev = get();
} while (!compareAndSet(prev, newValue));
return prev;
}
//incrementAndGet() : Add the original value in the instance in the atomic way 1 operation , And return the result of the final addition ;
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
//addAndGet(int delta) : Add the input value to the original value in the example in atomic mode , And return to the last knot fruit ;
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}test
public class AtomicIntegerTest {
static AtomicInteger sum = new AtomicInteger(0);
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() ->{
for (int j = 0; j < 10000; j++) {
// Atoms grow by themselves CAS
sum.incrementAndGet();
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sum.get());
}
}public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}CAS defects
- The spin CAS For a long time without success , Will give CPU It's very expensive
- Only one shared variable atomic operation can be guaranteed
- ABA problem
LongAdder/DoubleAdder
LongAccumulator

public static void main(String[] args) throws InterruptedException {
// Add up x+y
LongAccumulator accumulator = new LongAccumulator((x, y) -> x + y, 0);
ExecutorService executor = Executors.newFixedThreadPool(8);
// 1 To 9 Add up
IntStream.range(1, 10).forEach(i -> executor.submit(() -> accumulator.accumulate(i)));
Thread.sleep(2000);
System.out.println(accumulator.getThenReset());
}ABA Solutions to problems
Java The corresponding atomic reference class is provided AtomicStampedReference<V>;reference That is, the variables we actually store ,stamp It's the version , Each modification can be made through +1 Ensure version uniqueness . In this way, you can ensure that the version after each modification will also increase upward .


边栏推荐
- 2-6.自动化采集
- 【软件测试】包装简历从这几点出发、提升通过率
- [wechat applet] global style, local style, global configuration
- C# 43. 获取UDP可用端口
- Open source, innovators win, 2022 "science and innovation China" open source innovation list selection is fully open!
- 机器学习入门详解(一):理解监督学习中的最大似然估计
- Check the computer restart times and reasons
- Teach you to use cann to convert photos into cartoon style
- Vs2019 C MFC installation
- Weblux default IO threads
猜你喜欢

【Unity入门计划】基本概念-触发器 Trigger

475-82(230、43、78、79、213、198、1143)

【Unity入门计划】基本概念-2D碰撞体Collider 2D

【Unity入门计划】基本概念-预制件 Prefab

Eval and assert one sentence Trojan horse analysis

Teach you to use cann to convert photos into cartoon style

【Unity入门计划】制作我的第一个小游戏

Didi - dispatching
P1086 [NOIP2004 普及组第二题] 花生采摘

eval与assert一句话木马分析
随机推荐
文件详细操作
整数a按位取反(~)后的值为-(a+1)
P1086 [noip2004 popularization group question 2] peanut picking
【Unity入门计划】基本概念-预制件 Prefab
[ffmpeg] MP4 to YUV
Use cyclegan to train self-made data sets, popular tutorials, and get started quickly
深度学习之快速实现数据集增强的方法
Competition path design of beacon group
【软件测试】包装简历从这几点出发、提升通过率
How to reverse a stack with recursive functions and stack operations only
Open source, innovators win, 2022 "science and innovation China" open source innovation list selection is fully open!
Using one stack to sort another stack
A fast method of data set enhancement for deep learning
7.24 simulation summary
Problems easily ignored by POM
Introduction and installation of mongodb
Install homebrew, NVM and verdaccio to build a private NPM warehouse
In depth analysis of yolov7 network architecture
Polling, interrupt, DMA and channel
webflux默认io线程数