What's the Difference Between Boolean and AtomicBoolean in Java
In Java, both Boolean
and AtomicBoolean
are used to represent Boolean values, but they have different characteristics and use cases.
Boolean
is a wrapper class that represents a Boolean value as an object. It has two possible values: true
or false
. Boolean
objects are immutable, which means that once created, their value cannot be changed.
AtomicBoolean
, on the other hand, is a class that provides atomic operations on a Boolean value. Atomic operations are thread-safe, meaning that they can be safely used in a concurrent environment without the risk of race conditions or other synchronization issues. AtomicBoolean
provides methods such as get()
, set()
, compareAndSet()
, getAndSet()
, etc., which can be used to perform atomic operations on its underlying Boolean value.
The main difference between Boolean
and AtomicBoolean
is that Boolean
is immutable and cannot be changed once created, whereas AtomicBoolean
is mutable and can be modified using atomic operations.
AtomicBoolean
is typically used in concurrent programming scenarios where multiple threads may access and modify the same Boolean value. In such cases, using AtomicBoolean
can help avoid race conditions and other synchronization issues that may arise when multiple threads access and modify the same value concurrently.
On the other hand, Boolean
is typically used when you need a Boolean value as an object, for example, when passing it as an argument to a method that expects an object or when storing it in a collection that only accepts objects.
Here is an example of a Counter
class where you would typically use AtomicBoolean
:
public class Counter {
private AtomicBoolean isIncrementing = new AtomicBoolean(false);
private int count = 0;
public int increment() {
while (!isIncrementing.compareAndSet(false, true)) {
// wait until it's safe to increment
}
count++;
isIncrementing.set(false);
return count;
}
}
In short, whenever it's more than one thread could change a boolean value at the same time, it's better to use AtomicBoolean
for thread-safety.