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?
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
.
来源:https://stackoverflow.com/questions/23120811/atomic-read-and-write-of-long-and-double-values