Writing long and double is not atomic in Java?

前端 未结 6 1591
甜味超标
甜味超标 2020-12-02 18:37

Reading and writing of a single variable is atomic (language guarantee!), unless the variable is of type long or double.

I was reading

相关标签:
6条回答
  • 2020-12-02 19:06

    Read answer by maaartinus @ What operations in Java are considered atomic?
    Read answer by Jon Skeet @ When primitive datatypes not thread-safe in Java?

    As per the JLS you can make read and write operation on double and long to be atomic by declaring it as volatile. But this will not ensure ++ to be atomic. That needs concurrent.atomic package.
    Read this answer from Louis Wasserman.

    Also this blog and comments.

    0 讨论(0)
  • 2020-12-02 19:11

    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.

    0 讨论(0)
  • 2020-12-02 19:12

    Java long and double are not atomic in 32 bit machines, but atomic in 64 bit machines with some of the 64 bit JVMs. why its dependant on machine bit length? Because 32 bit machine needs two writes for long(as long is 64 bit). Read this for detailed info.

    0 讨论(0)
  • 2020-12-02 19:18

    Java programming language memory model, a single write to a non-volatile long or double value is treated as two separate writes: one to each 32-bit half. This can result in a situation where a thread sees the first 32 bits of a 64-bit value from one write, and the second 32 bits from another write.

    0 讨论(0)
  • 2020-12-02 19:29

    Just to clarify the situation for Java, doubles and longs are not read or written to atomically unless they're declared volatile

    JLS - Nonatomic Treatment of double and long

    0 讨论(0)
  • 2020-12-02 19:29

    Many programmers must have read this statement in "3.1.2. Non-Atomic 64bit Operations" in java concurrency in practice . I have referred the latest JLS 17.7. Non-Atomic Treatment of double and long. They still nowhere claim that 64 bit jVM are norm these days. So 64 bit operations are broken into 32 bit operations that break atomicity and dangerous to use in multithreaded environment until declared volatile . Long and double are 64 bit long in java. So writing and reading operations are not atomic in java.

    0 讨论(0)
提交回复
热议问题