Atomic Set vs LazySet vs 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.

发布了83 篇原创文章 · 获赞 0 · 访问量 858

猜你喜欢

转载自blog.csdn.net/michaelforgood/article/details/103478958
VS