简体   繁体   中英

Writing long and double is not atomic in Java?

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

I was reading a course's slides and I found that written. The class was about concurrency.

Can anyone explain to me why writing a long or a double is not an atomic operation? It really took me by surprise.

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.

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

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.

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.

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.

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 thisanswer from Louis Wasserman.

Also this blog and comments.

Atomic variable operation means that any thread can read/write from/to it without any trash

Non long / double read/write are atomic for x32 and some x64 because of hardware limitations. If volatile is used it makes it/add to it atomic

[Atomicity]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM