Is there any difference between a volatile
Object reference and AtomicReference
in case I would just use get()
and set()
-
There are several differences and tradeoffs:
Using an AtomicReference
get/set has the same JMM semantics as a volatile field(as the javadoc states), but the AtomicReference
is a wrapper around a reference, so any access to the field involves a further pointer chase.
The memory footprint is multiplied (assuming a compressed OOPs environment, which is true for most VMs):
AtomicReference
= 4b + 16b (12b object header + 4b ref field)AtomicReference
offers a richer API than a volatile reference. You can regain the API for the volatile reference by using an AtomicFieldUpdater
, or with Java 9 a VarHandle
. You can also reach straight for sun.misc.Unsafe
if you like running with scissors. AtomicReference
itself is implemented using Unsafe
.
So, when is it good to choose one over the other:
AtomicReference
/AtomicFieldUpdater
/Unsafe
where you tend to pay in readability and risk for your performance gain. If this not a sensitive area just go for AtomicReference
. Library writers typically use a mix of these methods depending on targeted JDKs, expected API restrictions, memory constraints and so on.