Atomic read and write of long and double values

 ̄綄美尐妖づ 提交于 2019-12-05 05:13:39

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.

user2864740

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!