Atomic Boolean

Get a clear understanding and use cases of the AtomicBoolean class and its differences with volatile boolean variables.

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 volatile variables.

The read and write methods i.e. get() and set() on instances of this class are similar in behavior to volatile variables i.e get() has the memory effect of reading a volatile variable and set() has the memory effect of writing a volatile variable.

Create a free account to view this lesson.

Continue your learning journey with a 14-day free trial.

By signing up, you agree to Educative's Terms of Service and Privacy Policy