Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 812
fmsf Avatar asked Feb 05 '09 19:02

fmsf


People also ask

Is reading a long double variable atomic?

Reads and writes are atomic for all variables declared volatile (including long and double variables).

Is long thread safe in Java?

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.

What are atomic types in Java?

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.

What is mean by atomic in Java?

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.


1 Answers

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.

like image 108
Don Branson Avatar answered Oct 02 '22 13:10

Don Branson