CAS :compare and swap非阻塞同步算法
来源:互联网 发布:centos yum nmap 编辑:程序博客网 时间:2024/06/14 09:24
CAS(乐观锁算法)
compare and swap,解决多线程并行情况下使用锁造成性能损耗的一种机制,CAS操作包含三个操作数——内存位置(V)、预期原值(A)和新值(B)。如果内存位置的值与预期原值相匹配,那么处理器会自动将该位置值更新为新值
do{ 备份旧数据; 基于旧数据构造新数据; }while(!CAS( 内存地址,备份的旧数据,新数据 ))
就是指当两者进行比较时,如果相等,则证明共享数据没有被修改,替换成新值,然后继续往下运行;如果不相等,说明共享数据已经被修改,放弃已经所做的操作,然后重新执行刚才的操作。容易看出 CAS 操作是基于共享数据不会被修改的假设,采用了类似于数据库的 commit-retry 的模式。当同步冲突出现的机会很少时,这种假设能带来较大的性能提升。
public class AtomicInteger extends Number implements java.io.Serializable { private static final long serialVersionUID = 6214790243416807050L; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset (AtomicInteger.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } private volatile int value; ,,,
+1操作
//+1操作 public final long getAndIncrement() { while (true) { long current = get(); long next = current + 1; //当+1操作成功的时候直接返回,退出此循环 //如果当前位置的值为current,更新为next if (compareAndSet(current, next)) return current; } }
0 0
- CAS :compare and swap非阻塞同步算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- java并发 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 并发方法之 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 非阻塞同步算法与CAS(Compare and Swap)无锁算法
- 配置和使用VS2013 MFC的若干问题
- ERROR:Simulator:861 - Failed to link the design
- 58同城高性能移动PUSH推送平台架构演进之路
- 归并排序
- [剑指offer]替换空格
- CAS :compare and swap非阻塞同步算法
- 使用for循环定义一个二维数组;(初学者)
- 两个不同模块中的jsp传值, 一个jsp页面中打开新的jsp页面, 新的jsp页面返回值给本jsp页面
- peachFuzzer error :Enable PageHeap
- transform函数转换字符串string的大小写
- C语言06指针进阶
- Apk加固
- Unity3D 学习日记(四)生成不重复的随机数
- [从头学数学] 第186节 仗剑题海载酒行(上)