gpt4 book ai didi

java - AtomicInteger weakCompareAndSet 上的 "spurious failure"是什么意思?

转载 作者:太空狗 更新时间:2023-10-29 22:38:40 25 4
gpt4 key购买 nike

Java AtomicInteger 类有一个方法 -

boolean weakCompareAndSet(int expect,int update)

它的文档说:

May fail spuriously.

这里的“虚假失败”是什么意思?

最佳答案

虚假地:没有明显的原因

根据 atomic包 javadoc:

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.


根据 this thread ,与其说是因为“硬件/操作系统”,不如说是因为 weakCompareAndSet 使用的底层算法:

weakCompareAndSet atomically sets the value to the given updated value if the current value == the expected value. May fail spuriously.

Unlike compareAndSet(), and other operations on an AtomicX, the weakCompareAndSet() operation does not create any happens-before orderings.

Thus, just because a thread sees an update to an AtomicX caused by a weakCompareAndSet doesn't mean it is properly synchronized with operations that occurred before the weakCompareAndSet().

You probably don't want to use this method, but instead should just use compareAndSet; as there are few cases where weakCompareAndSet is faster than compareAndSet, and there are a number of cases in which trying to optimizing your code by using weakCompareAndSet rather than compareAndSet will introduce subtle and hard to reproduce synchronization errors into your code.


关于的注意事项happens-before orderings :

The Java Memory Model (JMM) defines the conditions under which a thread reading a variable is guaranteed to see the results of a write in another thread.

The JMM defines an ordering on the operations of a program called happens-before.

Happens-before orderings across threads are only created by synchronizing on a common lock or accessing a common volatile variable.

In the absence of a happens-before ordering, the Java platform has great latitude to delay or change the order in which writes in one thread become visible to reads of that same variable in another.

关于java - AtomicInteger weakCompareAndSet 上的 "spurious failure"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/355365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com