JAVA的compareAndSet_java – AtomicReference.compareAndSet()用于确定什么?

说你有以下课程

public class AccessStatistics {

private final int noPages, noErrors;

public AccessStatistics(int noPages, int noErrors) {

this.noPages = noPages;

this.noErrors = noErrors;

}

public int getNoPages() { return noPages; }

public int getNoErrors() { return noErrors; }

}

并执行以下代码

private AtomicReference stats =

new AtomicReference(new AccessStatistics(0, 0));

public void incrementPageCount(boolean wasError) {

AccessStatistics prev, newValue;

do {

prev = stats.get();

int noPages = prev.getNoPages() + 1;

int noErrors = prev.getNoErrors;

if (wasError) {

noErrors++;

}

newValue = new AccessStatistics(noPages, noErrors);

} while (!stats.compareAndSet(prev, newValue));

}

在最后一行while(!stats.compareAndSet(prev,newValue))compareAndSet方法如何确定prev和newValue之间的相等性?是否需要AccessStatistics类来实现equals()方法?如果没有,为什么? javadoc为AtomicReference.compareAndSet声明了以下内容

Atomically sets the value to the given updated value if the current value == the expected value.

…但是这个断言似乎非常通用,我在AtomicReference上阅读的教程从未建议为包含在AtomicReference中的类实现equals().

如果包含在AtomicReference中的类需要实现equals(),那么对于比AccessStatistics更复杂的对象,我认为同步更新对象而不使用AtomicReference的方法可能会更快.

解决方法:

它比较使用==运算符完全比较refrerences.这意味着引用必须指向同一个实例.不使用Object.equals().

标签:java,concurrency,atomicity

来源: https://codeday.me/bug/20190607/1192000.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值