java atomicreference,何时使用AtomicReference(Java)?是真的有必要吗?

I have used AtomicLong many times but I have never needed to use AtomicReference

It seems that AtomicReference does either (I copied this code from another stackoverflow

question):

public synchronized boolean compareAndSet(List oldValue, List newValue) {

if (this.someList == oldValue) {

// someList could be changed by another thread after that compare,

// and before this set

this.someList = newValue;

return true;

}

return false;

}

Or

public synchronized boolean compareAndSet(List oldValue, List newValue) {

if (this.someList == oldValue || this.someList.equals(oldValue)) {

// someList could be changed by another thread after that compare,

// and before this set

this.someList = newValue;

return true;

}

return false;

}

Assume this.someList is marked volatile.

I'm not sure really which one it is because the javadoc and the code for that class are not clear if .equals is used.

Seeing how the above methods are not exactly that hard to write has anyone ever used AtomicReference?

解决方案

It's a reference, so that's what is compared. The documentation makes it very clear that it's an identity comparison, even using the == operation in its description.

I use AtomicReference and other atomic classes very frequently. Profiling shows that they perform better than the equivalent methods using synchronization. For example, a get() operation on an AtomicReference requires only a fetch from main memory, while an a similar operation using synchronized must first flush any values cached by threads to main memory and then perform its fetch.

The AtomicXXX classes provide access to native support for compare-and-swap (CAS) operations. If the underlying system supports it, CAS will be faster than any scheme cooked up with synchronized blocks in pure Java.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值