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.
Reads and writes are atomic for all variables declared volatile (including long and double variables).
So point is, in Java, long and double aren't thread safe. When multiple threads are going to access a long or a double value without synchronization, it can cause problems. To ensure atomic/thread safety, it is essential to use volatile to ensure changes made by one thread are visible to other threads.
The most commonly used atomic variable classes in Java are AtomicInteger, AtomicLong, AtomicBoolean, and AtomicReference. These classes represent an int, long, boolean, and object reference respectively which can be atomically updated.
Atomic is a toolkit of variable java. util. concurrent. atomic package classes, which assist in writing lock and wait-free algorithms with the Java language. An algorithm requiring only partial threads for constant progress is lock-free.
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.
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