Atomic Set vs LazySet vs WeakCompareAndSet

本文深入探讨Java中原子类的内存语义,包括get、set、lazySet、weakCompareAndSet、compareAndSet等方法如何影响内存可见性和一致性。特别关注weakCompareAndSet在更新计数器和统计信息时的特殊用途。

he memory effects for accesses and updates of atomics generally
follow the rules for volatiles, as stated in section 17.4 of
The Java™ Language Specification.

get has the memory effects of reading a

volatile variable.

set has the memory effects of writing (assigning) a

volatile variable.

lazySet has the memory effects of writing (assigning)

a volatile variable except that it permits reorderings with
subsequent (but not previous) memory actions that do not themselves
impose reordering constraints with ordinary non-volatile
writes. Among other usage contexts, lazySet may apply when
nulling out, for the sake of garbage collection, a reference that is
never accessed again.

weakCompareAndSet atomically reads and conditionally
writes a variable but does not
create any happens-before orderings, so provides no guarantees
with respect to previous or subsequent reads and writes of any
variables other than the target of the weakCompareAndSet.

compareAndSet

and all other read-and-update operations such as getAndIncrement
have the memory effects of both reading and
writing volatile variables.

The atomic classes also support method weakCompareAndSet,
which has limited applicability. On some platforms, the weak version
may be more efficient than compareAndSet in the normal case,
but differs in that any given invocation of the
weakCompareAndSet method may return false
spuriously (that is, for no apparent reason). A
false return means only that the operation may be retried if
desired, relying on the guarantee that repeated invocation when the
variable holds expectedValue and no other thread is also
attempting to set the variable will eventually succeed. (Such
spurious failures may for example be due to memory contention effects
that are unrelated to whether the expected and current values are
equal.) Additionally weakCompareAndSet does not provide
ordering guarantees that are usually needed for synchronization
control. However, the method may be useful for updating counters and
statistics when such updates are unrelated to the other
happens-before orderings of a program. When a thread sees an update
to an atomic variable caused by a weakCompareAndSet, it does
not necessarily see updates to any other variables that
occurred before the weakCompareAndSet. This may be
acceptable when, for example, updating performance statistics, but
rarely otherwise.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值