As far as I know reference assignment is atomic in a 64 bit JVM. Now, I assume the jvm doesn\'t use atomic pointers internally to model this, since otherwise there would be no n
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.
Your main confusion stems from the assumption that the additional “Atomic References” feature means exactly that, due to its name. But the AtomicReference
class offers far more, as it encapsulates a volatile
reference, which has stronger memory visibility guarantees in a multi-threaded execution.
Having an atomic reference update does not necessarily imply that a thread reading the reference will also see consistent values regarding the fields of the object reachable through that reference. All it guarantees is that you will read either the null
reference or a valid reference to an existing object that actually was stored by some thread. If you want more guarantees, you need constructs like synchronization, volatile
references, or an AtomicReference
.
AtomicReference
also offers atomic update operations like compareAndSet
or getAndSet
. These are not possible with ordinary reference variables.
Atomic reference assignment is in the specs.
Writes to and reads of references are always atomic, regardless of whether they are implemented as 32 or 64 bit values.
Quoted from JSR-133: Java(TM) Memory Model and Thread Specification, section 12 Non-atomic Treatment of double
and long
, http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf.
As the other answer outlines, the Java Memory Model states that references read/writes are atomic.
But of course, that is the Java language memory model. On the other hand: no matter if we talk Java or Scala or Kotlin or ... in the end everything gets compiled into bytecode.
There are no special bytecode instructions for Java. Scala in the end uses the very same instructions.
Leading to: the properties of that memory model must be implemented inside the VM platform. Thus they must apply to other languages running on the platform as well.