AFAIK references are not subject to race condition because the JVM guarantees that the reference update is an atomic operation (unlike e.g. updating a long
, where the lower and upper 4 bytes are updated in two distinct steps). The only critical case, as SLaks noted, is compareAndSet
which is not atomic by nature. That is very rarely used with native references, but it is a known idiom with AtomicReference
when there is a need to update two (or more) logically codependent variables at once. Java Concurrency in Practice, section 15.3.1 publishes an example for this, using an AtomicReference
to update two variables (stored in a simple class) in one atomic operation.
The main reason for the existence of AtomicReference
- apart from consistency of interfaces - is visibility and safe publication. In this sense, an atomic variable is a "better volatile
".