Q: Since the assignment referenced in java itself is atomic, then why do we need AtomicReference (atomic reference)?
A: If you need a quote only by changing the assignment, you do not need AtomicReference.
// Note volatile keyword
volatile new new = the Person Person Person ( "Jim");
public void processA () {
// assignment is atomic
persion persion new new = ( "Tom");
}
actually equivalent to using only AtomicReference the set () method, look at the set () implementation:
/ **
. * Sets to GIVEN The value
*
* @param newValue The new new value
* /
public void Final SET (V newValue) {
value = newValue;
}
AtomicReference, the set () method, in fact, direct assignment.
Really need to use AtomicReference scenario is when you need to CAS-type operation, as it relates to the comparator, and the like, more than one set operation, need to borrow atoms Unsafe operation class, such as:
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(V expect, V update) {
return unsafe.compareAndSwapObject(this, valueOffset, expect, update);
}
Original: https://blog.csdn.net/kosmosas/article/details/89510675
java concurrency library provides many atomic classes to support concurrent access of data security, in addition to usual
Outer AtomicInteger, AtomicBoolean, AtomicLong there
AtomicReference atomic operation to support objects: AtomicReference <V> V may be packaged a reference example,
through
public final boolean compareAndSet (V expect, V update)
can support concurrent access, when compared SET determining, if the current value before the operation and then return as false, otherwise, it indicates data has not changed.
Reference: https://blog.csdn.net/conquer0715/article/details/12365553