Skip to content

Can volatile make a non-atomic operation to atomic?

Posted in Education, and WhoCodeFirst

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.

If you enjoyed this article, Get email updates (It’s Free)
Translate »