简体   繁体   中英

When to use AtomicReference (Java)? Is it really necessary?

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<Object> oldValue, List<Object> 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<Object> oldValue, List<Object> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM