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?
It's not atomic because it's a multiple-step operation at the machine code level. That is, longs and doubles are longer than the processor's word length.
For example, an atomic read / write operation. Or atomic access to a property. But what does this mean? Generally, you can summarize atomic as "one at a time". For example, when accessing or mutating a property is atomic, it means that only one read or write operation can be performed at a time.
Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double). Reads and writes are atomic for all variables declared volatile (including long and double variables).
An atomic access is a term for a series of accesses to a memory region. Atomic accesses are used by managers when they would like to perform a sequence of accesses to a particular memory region, while being sure that the original data in the region are not corrupted by writes from other managers.
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.
Directly answering the question, using volatile
or AtomicLong will make actual read/write atomic.
However, excluding some specific cases these are often insufficient by themselves - that is they ensure that the read/write itself is atomic, but do not guarantee that the program is thread-safe.
To create truly atomic usage, larger atomic contexts must generally be established. In the most basic form this is done with synchronized
.
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