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

I used AtomicLong many times, but I never had to use AtomicReference

It seems that AtomicReference is doing 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; } 

Suppose this.someList is marked as volatile.

I am not sure what this is because javadoc and code for this class are not clear if .equals is used.

Seeing how the methods described above are not so difficult to write, has anyone ever used an AtomicReference?

+6
java concurrency atomic
source share
1 answer

This is a link, so what is being compared. The documentation is very clear that this is a comparison of identity, even using the == operation in its description.

I use AtomicReference and other atomic classes very often. Profiling shows that they work better than equivalent methods that use synchronization. For example, the get() operation on an AtomicReference only requires retrieving from main memory, while a similar operation using synchronized should first clear any values ​​cached by threads in main memory, and then perform a selection.

AtomicXXX classes provide access to native support for comparison and swap operations (CAS). If the underlying system supports it, CAS will be faster than any circuit prepared with synchronized blocks in pure Java.

+11
source share

All Articles