Does this mean that setting a reference is NOT an atomic operation in and of itself?
Setting a reference variable is atomic, but an atomic operation is not necessarily thread-safe. Let me explain.
Atomic means that any observer (thread) sees the either the old value or the new value of the variable, and not something else. It does not mean that all observers see the new value when they look at the variable. (And as @Tom points out, atomicity of the reference variable says nothing about the atomicity properties of the object that it references.)
For all observers to see the new value in the variable, there needs to be some synchronization going on. For an update to a variable, this will happen if:
- the variable is declared as
volatile
, or
- access / updates to the variable are synchronized by the same primitive monitor lock.
A variable that is wrapped in the relevant "AtomicXxx" class will also be thread-safe, though you normally use one of these classes if you want to avoid locks and you want to do things such as atomic "compare-and-replace".
Again though, this only applies to the thread-safety of the object's reference. If the object's state is not also properly synchronized, a thread could well see stale values for the object's attributes, etcetera.
LinkedList
may allow you to get away with this if it is empty). – Filibegnew java.awt.Point(1, 2)
, I may be able to read the object in another thread but thex
andy
fields may still be zero. – Filibeg