DEV Community

k@k
k@k

Posted on

Can volatile make a non-atomic operation to atomic?

This question is also not easy to answer because volatile is not about atomicity, but there are cases where you can use a volatile variable to make the operation atomic.

One example is having a long field in your class. If you know that a long field is accessed by more than one thread e.g. a counter, a price field or anything, you better make it volatile.

Why? because reading to a long variable is not atomic in Java and done in two steps, If one thread is writing or updating long value, it’s possible for another thread to see half value (fist 32-bit). While reading/writing a volatile long or double (64 bit) is atomic.

Discussion (0)