incrementandget java_CAS指令 incrementAndGet方法 JAVA非阻塞同步

博客以Java代码为例,展示了使用volatile变量进行并发计数时,因只能保证可见性,实际输出小于预期。介绍了改进方法,即使用CAS指令,通过AtomicInteger类的incrementAndGet方法实现原子操作,解决并发计数问题,同时指出存在“ABA”问题,可使用传统互斥同步方法解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一个使用volatile的例子

public class VolatileTest {

public static volatile int race=0;

public static void increase(){

race++;

}

private static final int THREADS_COUNT=20;

public static void main(String[] args){

Thread[] threads=new Thread[THREADS_COUNT];

for(int i=0;i

threads[i]=new Thread(new Runnable(){

public void run(){

for(int i=0;i<10000;i++){

increase();

}

}

});

threads[i].start();

}

while(Thread.activeCount()>1)

Thread.yield();

System.out.println(race);

}

}

预期输出200000

但是实际输出总是小于200000

如148407

原因:volatile变量只能保证可见性

主要用于下列场景:

1、运算结果不依赖变量的当前值

2、变量不需要与其他变量共同参与不变约束

改进方法

使用CAS指令

CAS中有三个操作树,分别是内存位置V、旧的预期值A、新值B

当且仅当V符合A时,处理器才用B更新V

不论更新成功与否返回值均为V(更新前的值)

此指令的操作是原子操作

public class AtomicTest {

public static AtomicInteger race = new AtomicInteger(0);

public static void increase() {

race.incrementAndGet();

}

private static final int THREADS_COUNT = 20;

public static void main(String[] args) {

Thread[] threads = new Thread[THREADS_COUNT];

for (int i = 0; i < THREADS_COUNT; i++) {

threads[i] = new Thread(new Runnable() {

public void run() {

for (int i = 0; i < 10000; i++) {

increase();

}

}

});

threads[i].start();

}

while (Thread.activeCount() > 1)

Thread.yield();

System.out.println(race);

}

}

输出:200000

看下incrementAndGet的实现

/**

* Atomically increments by one the current value.

*

* @return the updated value

*/

public final int incrementAndGet() {

for (;;) {

int current = get();

int next = current + 1;

if (compareAndSet(current, next))

return next;

}

}

再看下compareAndSet的实现

/**

* Atomically sets the value to the given updated value

* if the current value {@code ==} the expected value.

*

* @param expect the expected value

* @param update the new value

* @return true if successful. False return indicates that

* the actual value was not equal to the expected value.

*/

public final boolean compareAndSet(int expect, int update) {

return unsafe.compareAndSwapInt(this, valueOffset, expect, update);

}

遗留问题:“ABA”问题

概率低,可以使用传统的互斥同步方法解决

参考:

深入理解Java虚拟机:JVM高级特性与最佳实践, 作者: 周志明, 品牌: 机械工业出版社, 版本: 第1版, 机械工业出版社

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值