当前位置:网站首页>cas and spin locks (is lightweight locks spin locks)
cas and spin locks (is lightweight locks spin locks)
2022-07-31 20:10:00 【Full stack programmer webmaster】
大家好,又见面了,我是你们的朋友全栈君.
文章目录
什么是CAS机制(compare and swap)
CAS算法的作用:An algorithm to solve the performance loss caused by using locks under multi-threading conditions,保证了原子性,This atomic operation is made by CPU来完成的 CAS的原理:CASThe algorithm has three operands,by value in memory(V)、Expected raw value(A)、修改后的新值. (1)If the value in memory is equal to the expected original value, The modified new value is saved to memory. (2)If the value in memory is not equal to the expected original value,说明共享数据已经被修改,放弃已经所做的操作,然后重新执行刚才的操作,直到重试成功. 注意: (1)Expected raw value(A)It is read from the offset position into the L3 cacheCPU处理的值,The new modified value is the expected original valueCPUProcessing is temporarily stored in CPUvalue in the L3 cache,Whereas memory specifies the original value in the offset location. (2)Compares whether the value read from the specified offset into the cache is equal to the value at the specified memory offset,If equal, modify the value at the specified memory offset,This operation is implemented by an atomic instruction in the underlying assembly of the operating system,保证了原子性
- JVM中CAS是通过UnSafe类来调用操作系统底层的CAS指令实现.
- CASIt is designed based on the idea of optimistic locking,It does not cause blocking,synchronize会导致阻塞.
原子类
java.util.concurrent.atomicThe atomic classes under the package are usedCAS算法.而java.util.concurrentImplementations of most classes in , use these atomic classes directly or indirectly. Unsafe类使Java拥有了类似CThe ability of language pointers to manipulate memory spaces,At the same time, it also brings security problems of pointers.
AtomicInteger原子类
AtomicIntegerEqual atomic classes are not usedsynchronized锁,而是通过volatile和CAS(Compare And Swap)Resolve thread safety issues for resources. (1)volatile保证了可见性和有序性 (2)CAS保证了原子性,And it is a lock-free operation,提高了并发效率.
//创建Unsafe类的实例
private static final Unsafe unsafe = Unsafe.getUnsafe();
//成员变量valueis the offset in the memory address from the first address of the current object, The concrete assignment is made in the static code block below
private static final long valueOffset;
static {
try {
//类加载的时候,Get variables in static code blocksvalue的偏移量
valueOffset = unsafe.objectFieldOffset
(AtomicInteger.class.getDeclaredField("value"));
} catch (Exception ex) {
throw new Error(ex); }
}
// 当前AtomicInteger原子类的value值
private volatile int value;
//类似于i++操作
public final int getAndIncrement() {
//this代表当前AtomicInteger类型的对象,valueOffset表示valueThe offset of the member variable
return unsafe.getAndAddInt(this, valueOffset, 1);
}
================================上方为AtomicInteger类中的方法,下方为Unsafe类中的方法=========================================================
//此方法的作用:Get the memory address as the first address of the atomic object+原子对象valueProperty address offset, 并将该变量值加上delta
public final int getAndAddInt(Object obj, long offset, int delta) {
int v;
do {
//Get variable value by object and offset as expected value,Compares with the original when modifying the value at this memory offset
//used in this methodvolatile的底层原理,保证了内存可见性,All threads get variables from memoryvlaue的值,All threads see the same value.
v= this.getIntVolatile(obj, offset);
/* while中的compareAndSwapInt()方法尝试修改v的值,具体地, 该方法也会通过obj和offset获取变量的值 如果这个值和v不一样, 说明其他线程修改了obj+offset地址处的值, 此时compareAndSwapInt()返回false, 继续循环 如果这个值和v一样, 说明没有其他线程修改obj+offset地址处的值, 此时可以将obj+offset地址处的值改为v+delta, compareAndSwapInt()返回true, 退出循环 Unsafe类中的compareAndSwapInt()方法是原子操作, 所以compareAndSwapInt()修改obj+offset地址处的值的时候不会被其他线程中断 */
} while(!this.compareAndSwapInt(obj, offset, v, v + delta));
return v;
}
操作步骤: (1)获取AtomicIntegerThe first address of the object specifies the value at the offset position,作为期望值. (2)take outAtomicIntegerThe value at the object offset,Determine whether it is equal to the expected value,Modify if equalAtomicIntegerThe value at the memory offset,不相等就返回false,Perform the first step again,Retrieves the value at the specified offset in memory. (3) 如果相等,then modify the value and returntrue. 注意:从1、2步可以看CASThe lock implemented by the mechanism is a spin lock,If the thread has been unable to acquire the lock,则一直自旋,不会阻塞
CAS和syncronized的比较
CAS线程不会阻塞,Threads spin in unison syncronized会阻塞线程,会进行线程的上下文切换,会由用户态切换到内核态,The user mode context needs to be saved before switching,The kernel mode returns to user mode,Again the saved context needs to be restored,非常消耗资源.
CAS的缺点
(1)ABA问题 如果一个线程t1The value of a shared variable is being modifiedA,But haven't changed it yet,此时另一个线程t2获取到CPU时间片,The value of the variable will be sharedA修改为B,然后又修改为A,此时线程t1Checking that the value of the shared variable has not changed,但是实际上却变化了. 解决办法: 使用版本号,在变量前面追加上版本号,每次变量更新的时候把版本号加1,那么A-B-A 就会变成1A-2B-3A.从Java1.5开始JUC包里提供了一个类AtomicStampedReference来解决ABA问题.AtomicStampedReference类的compareAndSet方法作用是首先检查当前引用是否等于预期引用,并且当前版本号是否等于预期版本号,如果全部相等,则以原子方式将该引用和该标志的值设置为给定的更新值.
(2)Long cycle time will be more expensive:Spin retry time,会给CPU带来非常大的执行开销
(3)只能保证一个共享变量的原子操作,Atomicity of operations on multiple variables at the same time is not guaranteed 解决办法: 从Java1.5开始JDK提供了AtomicReference类来保证引用对象之间的原子性,你可以把多个变量放在一个对象里来进行CAS操作
CAS使用注意事项
(1)CAS需要和volatile配合使用
CASOnly the atomicity of variables is guaranteed,Memory visibility of variables is not guaranteed.CASWhen getting the value of a shared variable,需要和volatile配合使用,来保证共享变量的可见性
(2)CASSuitable for low concurrency、多核CPU的情况
CPUIn the case of multi-core, it can be executed at the same time,Fail if it doesn't fit.And the concurrency is too high,Will cause spin retries to be expensiveCPU资源
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127875.html原文链接:https://javaforall.cn
边栏推荐
- sqlite3 simple operation
- 【AcWing】The 62nd Weekly Match 【2022.07.30】
- MySQL---operator
- How to change npm to Taobao mirror [easy to understand]
- AI 自动写代码插件 Copilot(副驾驶员)
- Embedded development has no passion, is it normal?
- INeuOS industrial Internet operating system, the equipment operational business and "low code" form development tools
- 高通cDSP简单编程例子(实现查询高通cDSP使用率、签名),RK3588 npu使用率查询
- 获取抖音视频详情 API
- GAC Honda Safety Experience Camp: "Danger" is the best teacher
猜你喜欢
Redis Overview: Talk to the interviewer all night long about Redis caching, persistence, elimination mechanism, sentinel, and the underlying principles of clusters!...
Count characters in UTF-8 string function
[Open class preview]: Research and application of super-resolution technology in the field of video image quality enhancement
MySQL---单行函数
leetcode: 6135. The longest ring in the graph [inward base ring tree + longest ring board + timestamp]
Apache EventMesh 分布式事件驱动多运行时
学生管理系统第一天:完成登录退出操作逻辑 PyQt5 + MySQL5.8
STM32 full series development firmware installation guide under Arduino framework
全网一触即发,自媒体人的内容分发全能助手——融媒宝
顺序表的实现
随机推荐
Thymeleaf是什么?该如何使用。
INeuOS industrial Internet operating system, the equipment operational business and "low code" form development tools
全平台GPU通用AI视频补帧超分教程
MySQL---sort and pagination
Socket回顾与I/0模型
【AcWing】The 62nd Weekly Match 【2022.07.30】
-xms -xmx(information value)
Shell 脚本 快速入门到实战 -02
What is Thymeleaf?How to use.
Given an ip address, how does the subnet mask calculate the network number (how to get the ip address and subnet mask)
老牌音乐播放器 WinAmp 发布 5.9 RC1 版:迁移到 VS 2019 完全重建,兼容 Win11
【愚公系列】2022年07月 Go教学课程 023-Go容器之列表
ReentrantLock原理(未完待续)
Qualcomm cDSP simple programming example (to query Qualcomm cDSP usage, signature), RK3588 npu usage query
sqlite3 simple operation
Efficient Concurrency: A Detailed Explanation of Synchornized's Lock Optimization
Realize serial port receiving data based on STM32 ring queue
[PIMF] OpenHarmony Thesis Club - Inventory of the open source Hongmeng tripartite library [3]
matplotlib ax bar color 设置ax bar的颜色、 透明度、label legend
grep命令 笔试题