I have simple general question about AtomicReference.
Why use AtomicReference if reference assignment is atomic in java?
Also I would like to ask if reference assigment is atomic in 64-bit VMs?
Do we need volatile to have reference assigment atomic?
An atomic reference is ideal to use when you need to share and change the state of an immutable object between multiple threads. That is a super dense statement, so I will break it down a bit. First, an immutable object is an object that is effectively not changed after construction.
First of all, reference assignment is atomic because the specification says so. Besides that, there is no obstacle for JVM implementors to fulfill this constraint, as 64 Bit references are usually only used on 64 Bit architectures, where atomic 64 Bit assignment comes for free.
Reference assignment is atomic. Interlocked. Exchange does not do only reference assignment. It does a read of the current value of a variable, stashes away the old value, and assigns the new value to the variable, all as an atomic operation.
Variables shared between multiple threads (e.g., instance variables of objects) have atomic assignment guaranteed by the Java language specification for all data types except for long s and double s.
Why use AtomicReference if reference assignment is atomic in java?
You need it when the decision on which the creation of the new value is based can depend on the previous value of the reference. For instance when implementing some LinkedList like data structure you wan't to set the head to a new node which refers to the previous node. In the time between reading the previous node and setting head to the new one some other thread could have concurrently updated the head reference's value. If our thread would not be aware of this change, it would go lost.
Do we need volatile to have reference assigment atomic?
The operation itself would be performed atomic on the CPU core executing it but there are no guarantees that threads on other cores will be aware of it on the next read.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With