I have simple general question about AtomicReference.
Why use AtomicReference if reference assignment is atomic in java?
Also I would like to ask if referen
My previous answer was incorrect, as explained in the comment by juancn:
That's the difference between
Atomic*
classes and volatile access. Reference assignment is atomic only in the sense that no word tearing can occur, but there's no visibility or reordering guarantees. Java guarantees atomic writes in this restricted sense for all primitive types and references but not for long/double (although in 64bit VMs I think they're always atomic).
Previous answer
It is necessary, mainly for compareAndSet
and getAndSet
methods. You cannot do this atomically otherwise (2 operations are needed).