I know the differences between both in terms of visibility and ensuring atomic access and atomic operations. But I was wondering, if for example I only needed to use Volatile, and Atomic wasn't necessary, is there an advantage (maybe memory or efficiency wise) to using just Volatile? Or can I just use Atomic instead?
-
1If you know the difference, then you should know that they are meant to be used for completely different usage. volatile accesses should not be used to replace atomic ones. If you write a parallel problem, then you likely need atomicity. If you write hardware-related program (eg. control of remote devices using memory) then you need volatile. volatile can also be used when you want to debug an optimized code so to be able to read the variable. volatile does not ensure atomicity and it is unsafe in a parallel programs without additional synchronizations like memory barriers. – Jérôme Richard Feb 08 '22 at 12:03
-
2What programming language are you asking about? The exact meaning of "volatile" and "atomic" can be different in different language. (And, if you're comparing C++ to any other language, the meaning of "volatile" may be _completely_ different!!) – Solomon Slow Feb 08 '22 at 14:33
-
@JérômeRichard oh i see! So, in general, Atomic values can't necessarily do everything than volatile values do? I thought that volatile values are a more specific implementation of Atomic values. – Tobiken Feb 08 '22 at 15:38
-
1@SolomonSlow oh, well then I'm using Java – Tobiken Feb 08 '22 at 15:38
-
I was focusing on C/C++. However, it turns out it looks the same in Java. See: https://stackoverflow.com/questions/19744508/volatile-vs-atomic . – Jérôme Richard Feb 08 '22 at 15:43
-
2@JérômeRichard: a volatile in Java has the same semantics as a C++ atomic using memory_order_seq_cst. – pveentjer Feb 09 '22 at 03:40
1 Answers
The get()
and set(...)
methods of a Java AtomicWhatever
object have exactly the same semantics as assignments to, and reads from, a volatile
variable. So in effect, "Atomic" is a superset of "volatile."
The semantics are simple: If one thread assigns a volatile
variable or, if it set(...)
s an AtomicXxxxxx
object, then whatever else it did before that assignment is guaranteed to be visible to some other thread after the other thread subsequently reads the same variable or, after it subsequently get()
s from the same object.
volatile
was in the language from the beginning. Atomics are newer. Some programmers will tell you that because atomics effectively are "volatile," that we don't need the volatile
keyword anymore, and you should not use it. That's a matter of opinion, but if you're working on a team with other developers, it's best to use the same style and the same patterns that everybody else on the team uses.

- 25,130
- 5
- 37
- 57