Thursday 4 May 2017

AtomicBoolean in Java

A boolean value that may be updated atomically.
The AtomicBoolean class provides you with a boolean variable which can be read and written atomically, and which also contains advanced atomic operations like compareAndSet().

When do we need AtomicBoolean?
When multiple threads need to check and change the boolean.
Example:
if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:
if (atomicInitialized.compareAndSet(false, true)) {
     initialize();
}

Is synchronized volatile boolean equal to atomicBoolean?
Is this the case where AtomicBoolean should be used?
Yes it is.
If yes, why can't this be handled by using synchronized?

It is functionnaly equivalent, but AtomicBoolean does not use a lock, which can be more efficient under moderate contention.

Creating an AtomicBoolean
AtomicBoolean atomicBoolean = new AtomicBoolean();
It will create a new AtomicBoolean with the value false.

AtomicBoolean atomicBoolean = new AtomicBoolean(true);
It will create a new AtomicBoolean with the value true.

Getting the AtomicBoolean's Value
AtomicBoolean atomicBoolean = new AtomicBoolean(true);

boolean value = atomicBoolean.get();
After getting the value variable will contain the value true.

Setting the AtomicBoolean's Value
AtomicBoolean atomicBoolean = new AtomicBoolean(true);

atomicBoolean.set(false);
After setting, AtomicBoolean variable will contain the value false.

Swapping the AtomicBoolean's Value
We can swap the value of an AtomicBoolean using the getAndSet() method. The getAndSet() method returns the AtomicBoolean's current value, and sets a new value for it.
AtomicBoolean atomicBoolean = new AtomicBoolean(true);

boolean oldValue = atomicBoolean.getAndSet(false);

After executing getAndSet, oldValue variable will contain the value true, and the AtomicBoolean instance will contain the value false. The code effectively swaps the value false for the AtomicBoolean's current value which is true.

Compare and Set AtomicBoolean's Value
The method compareAndSet() allows you to compare the current value of the AtomicBoolean to an expected value, and if current value is equal to the expected value, a new value can be set on the AtomicBoolean. The compareAndSet() method is atomic, so only a single thread can execute it at the same time. Thus, the compareAndSet() method can be used to implemented simple synchronizers like locks.

AtomicBoolean atomicBoolean = new AtomicBoolean(true);

boolean expectedValue=true;
boolean newValue     =false;

boolean wasNewValueSet=atomicBoolean.compareAndSet(expectedValue, newValue);
This snippet compares the current value of the AtomicBoolean to true and if the two values are equal, sets the new value of the AtomicBoolean to false.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...