AtomicBoolean supports atomic operations on underlying boolean variable. It have get and set methods that work like reads and writes on volatile variables. That is, a set has a happens-before relationship with any subsequent get on the same variable.
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.
synchronization is blocking synchronization, which utilizes locks to prevent conflicts. between competing processes. This thesis explores and compares the alternative of non- blocking synchronization, which does not employ locks, but instead complex algorithms. using hardware-based primitive atomic operations.
A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at the same time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.
I was trying to cut thread contention in my code by replacing some synchronized
blocks with AtomicBoolean
.
Here's an example with synchronized
:
public void toggleCondition() {
synchronized (this.mutex) {
if (this.toggled) {
return;
}
this.toggled = true;
// do other stuff
}
}
And the alternative with AtomicBoolean
:
public void toggleCondition() {
if (!this.condition.getAndSet(true)) {
// do other stuff
}
}
Taking advantage of AtomicBoolean
's CAS property should be way faster than relying on synchronization so I ran a little micro-benchmark.
For 10 concurrent threads and 1000000 iterations, AtomicBoolean
comes in only slightly faster than synchronized
block.
Average time (per thread) spent on toggleCondition() with AtomicBoolean: 0.0338
Average time (per thread) spent on toggleCondition() with synchronized: 0.0357
I know micro-benchmarks are worth what they're worth but shouldn't the difference be higher?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With