Brooks Brooks - 1 year ago 150
Java Question

Why can't AtomicBoolean be a replacement for Boolean?

The Oracle JDK Javadoc for AtomicBoolean states:

A boolean value that may be updated atomically. See the
java.util.concurrent.atomic package specification for description of
the properties of atomic variables. An AtomicBoolean is used in
applications such as atomically updated flags, and cannot be used as a
replacement for a Boolean.

A colleague and I were trying to figure out a use-case where the AtomicBoolean can't be a substitute and the only thing we can think of is that there are methods the Boolean object has that the AtomicBoolean does not.

Is that the only reason or was there something else in mind when that was written?

Answer Source

Boolean is the wrapper class around the primitive boolean. It may be automatically created from a boolean by the compiler (boxing conversion) or converted to a boolean (unboxing conversion). This is not the case for AtomicBoolean where it is a separate class designed for concurrency purposes.

Hence the two classes have different semantics at the language level:

Boolean b = new Boolean(true);
AtomicBoolean ab = new AtomicBoolean(true);
System.out.println(true == b);  // automatic unboxing of Boolean variable
System.out.println(true == ab);  // compiler error