Atomic Boolean
Get a clear understanding and use cases of the AtomicBoolean class and its differences with volatile boolean variables.
We'll cover the following...
If you are interviewing, consider buying our number#1 course for Java Multithreading Interviews.
Explanation
The AtomicBoolean
class belonging to Java’s java.util.concurrency.atomic
package represents a boolean value that can be updated and modified atomically. The Atomic*
family of classes extend the notion of volatile
variables that are designed to be operated upon without locking using machine-level atomic instructions available on modern processors. However, on other platforms some form of internal locking may be used to serialize thread access.
Atomic*
classes including AtomicBoolean
offer a method compareAndSet(expectedValue, updatedValue)
to conditionally update the value of the variable to updatedValue
if it is set to expectedValue
in one go, i.e. atomically. All read-and-update methods except for lazySet()
and weakCompareAndSet()
have memory effects equivalent of both reading and writing ...