Search code examples
javamultithreadingatomic

Atomic read and write of long and double values


long and double read and write operation are not atomic because of their size more than cpu word size.

So could I get atomic read and write operation of long and double if I have 64 bit machine?


Solution

  • so could i get atomic read and write operation of long and double if i have 64 bit machine ?

    The answer is "maybe". The answer depends on the JVM implementation as well as the machine architecture. To quote from the Java Language definition 17.7:

    Some implementations may find it convenient to divide a single write action on a 64-bit long or double value into two write actions on adjacent 32-bit values. For efficiency's sake, this behavior is implementation-specific; an implementation of the Java Virtual Machine is free to perform writes to long and double values atomically or in two parts.

    Implementations of the Java Virtual Machine are encouraged to avoid splitting 64-bit values where possible. Programmers are encouraged to declare shared 64-bit values as volatile or synchronize their programs correctly to avoid possible complications.

    Here's a great page about Ensure atomicity when reading and writing 64-bit values.