What does AtomicBoolean do that a volatile boolean cannot achieve?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
They are just totally different. Consider this example of a
volatileinteger:If two threads call the function concurrently,
imight be 5 afterwards, since the compiled code will be somewhat similar to this (except you cannot synchronize onint):If a variable is volatile, every atomic access to it is synchronized, but it is not always obvious what actually qualifies as an atomic access. With an
Atomic*object, it is guaranteed that every method is “atomic”.Thus, if you use an
AtomicIntegerandgetAndAdd(int delta), you can be sure that the result will be10. In the same way, if two threads both negate abooleanvariable concurrently, with anAtomicBooleanyou can be sure it has the original value afterwards, with avolatile boolean, you can’t.So whenever you have more than one thread modifying a field, you need to make it atomic or use explicit synchronization.
The purpose of
volatileis a different one. Consider this exampleIf you have a thread running
loop()and another thread callingstop(), you might run into an infinite loop if you omitvolatile, since the first thread might cache the value of stop. Here, thevolatileserves as a hint to the compiler to be a bit more careful with optimizations.