0 votes
in JAVA by
Can volatile make a non-atomic operation to atomic?

1 Answer

0 votes
by
This another good question I love to ask on volatile, mostly as a follow-up of the previous question. 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 I have seen 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.

Related questions

0 votes
asked May 5, 2021 in JAVA by SakshiSharma
0 votes
asked Apr 10, 2021 in JAVA by Robindeniel
...