当前位置:网站首页>CAS操作
CAS操作
2022-07-25 07:54:00 【季风泯灭的季节】
什么是 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 {
/**
* 获取 Unsafe 对象 * @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;
}
/**
* 获取字段的内存偏移量
* @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 本质是一条CPU 的原子指令,由操作系统硬件来保证。不同操作系统和不同CPU会有不同的 实现。
CAS 在 Java 语言中的应用
在 Java 编程中我们通常不会直接使用到 CAS,都是通过 JDK 封装好的并发工具类来间接使用的,这些并发工具类都在java.util.concurrent包中。
J.U.C 是
java.util.concurrent的简称,也就是大家常说的 Java 并发编程工具包,面试常考,非常非常重要。
- 基本类型:AtomicInteger、AtomicLong、AtomicBoolean;
- 引用类型:AtomicReference、AtomicStampedRerence、AtomicMarkableReference;
- 数组类型:AtomicIntegerArray、AtomicLongArray、AtomicReferenceArray
- 对象属性原子修改器:AtomicIntegerFieldUpdater、AtomicLongFieldUpdater、AtomicReferenceFieldUpdater
- 原子类型累加器(jdk1.8增加的类):DoubleAccumulator、DoubleAdder、 LongAccumulator、LongAdder、Striped64
//以原子的方式将实例中的原值加1,返回的是自增前的旧值;
public final int getAndIncrement() {
return unsafe.getAndAddInt(this, valueOffset, 1);
}
//getAndSet(int newValue):将实例中的值更新为新值,并返回旧值; 、
public final boolean getAndSet(boolean newValue) {
boolean prev;
do {
prev = get();
} while (!compareAndSet(prev, newValue));
return prev;
}
//incrementAndGet() :以原子的方式将实例中的原值进行加1操作,并返回最终相加后的结果;
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
//addAndGet(int delta) :以原子方式将输入的数值与实例中原本的值相加,并返回最后的结 果;
public final int addAndGet(int delta) {
return unsafe.getAndAddInt(this, valueOffset, delta) + delta;
}测试
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++) {
// 原子自增 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缺陷
- 自旋 CAS 长时间地不成功,则会给 CPU 带来非常大的开销
- 只能保证一个共享变量原子操作
- ABA 问题
LongAdder/DoubleAdder
LongAccumulator

public static void main(String[] args) throws InterruptedException {
// 累加 x+y
LongAccumulator accumulator = new LongAccumulator((x, y) -> x + y, 0);
ExecutorService executor = Executors.newFixedThreadPool(8);
// 1到9累加
IntStream.range(1, 10).forEach(i -> executor.submit(() -> accumulator.accumulate(i)));
Thread.sleep(2000);
System.out.println(accumulator.getThenReset());
}ABA问题的解决方案
Java提供了相应的原子引用类AtomicStampedReference<V>;reference即我们实际存储的变量,stamp是版本,每次修改可以通过+1保证版本唯一性。这样就可以保证每次修改后的版本也会往上递增。


边栏推荐
- [paper notes] progressive layered extraction (PLE): a novel multi task learning (MTL) model for personalized
- 查看电脑重启次数、原因
- [unity introduction program] basic concepts GameObject & components
- Leetcode (Sword finger offer) - 04. search in two-dimensional array
- 2-6. Automatic acquisition
- Implement hot post | community project with timed tasks and cache
- Tunnel broadcasting and wireless trunking communication broadcasting system - the case of Tiantaishan tunnel
- while(~scanf(“%d“, &n)) 等价于 while(scanf(“%d“,&n)!=EOF)
- C# 43. 获取UDP可用端口
- A queue of two stacks
猜你喜欢
![[unity introduction program] basic concepts - 2D collider collider 2D](/img/cf/a546238a5eaf4707006ecf1b7f19c6.png)
[unity introduction program] basic concepts - 2D collider collider 2D

Hikaricp connection pool does not operate for a period of time, and the data is automatically disconnected

Nano data, football data, football match scores, sports data API, Qatar world cup

Today in history: Intel was founded; The first photo was posted on the world wide web; EBay spins off PayPal

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!

轮询、中断、DMA和通道
![[unity entry program] make my first little game](/img/e7/5dcb113c7fabd73ed632fb29619369.png)
[unity entry program] make my first little game

Eval and assert one sentence Trojan horse analysis

Have you got the advanced usage of pytest?
随机推荐
【论文笔记】Progressive Layered Extraction (PLE): A Novel Multi-Task Learning (MTL) Model for Personalized
滴滴 - eta(Estimate the Travel Time)
Supplementary notes on Relevant Issues of complete model group
深度学习训练和测试时出现问题:error: the following arguments are required: --dataroot,解决:训练文件的配置方法和测试文件的配置方法
【Unity入门计划】基本概念-预制件 Prefab
oracle 触发器创建
Problems easily ignored by POM
【音视频】图片YUV数据格式
文件详细操作
C 43. Get UDP available ports
In depth analysis of yolov7 network architecture
Open source, innovators win, 2022 "science and innovation China" open source innovation list selection is fully open!
P1049 [noip2001 popularization group t4] packing problem
Weblux default IO threads
CSDN custom T-shirts are waiting for you to get, and the benefits of new programmer are coming!
【Unity入门计划】界面介绍(1)-Scene视图
Load capacity - sorting out the mind map that affects load capacity
Using one stack to sort another stack
app耗电量测试
Calculation formula of cross entropy