What does AtomicBoolean do that a volatile boolean cannot achieve?
What does AtomicBoolean do that a volatile boolean cannot achieve?
Boolean primitive type is atomic for write and read operations, volatile guarantees the happens-before principle. So if you need a simple get() and set() then you don't need the AtomicBoolean.
On the other hand if you need to implement some check before setting the value of a variable, e.g. "if true then set to false", then you need to do this operation atomically as well, in this case use compareAndSet and other methods provided by AtomicBoolean, since if you try to implement this logic with volatile boolean you'll need some synchronization to be sure that the value has not changed between get and set.
A lot of the answers here are overly complicated, confusing, or just wrong. For example:
… if you have multiple threads modifying the boolean, you should use an
AtomicBoolean.
That's incorrect as a general statement.
If a variable is volatile, every atomic access to it is synchronized …
That is not correct; synchronization is a separate thing altogether.
The simple answer is that AtomicBoolean allows you to prevent race conditions in certain operations that require reading the value and then writing a value that depends on what you read; it makes such operations atomic (i.e. it removes the race condition where the variable might change between the read and the write)—hence the name.
If you are just reading and writing the variable where the writes don't depend on a value you just read, volatile will work just fine, even with multiple threads.
Both are of same concept but in atomic boolean it will provide atomicity to the operation in case the cpu switch happens in between.