Consider two methods a() and b() that cannot be executed at the same time. The synchronized key word can be used to achieve this as below. Can I achieve the same effect using AtomicBoolean as per the code below this?
final class SynchonizedAB {
synchronized void a(){
// code to execute
}
synchronized void b(){
// code to execute
}
}
Attempt to achieve the same affect as above using AtomicBoolean:
final class AtomicAB {
private AtomicBoolean atomicBoolean = new AtomicBoolean();
void a(){
while(!atomicBoolean.compareAndSet(false,true){
}
// code to execute
atomicBoolean.set(false);
}
void b(){
while(!atomicBoolean.compareAndSet(false,true){
}
// code to execute
atomicBoolean.set(false);
}
}
No, since
synchronizedwill block, while with theAtomicBooleanyou'll be busy-waiting.Both will ensure that only a single thread will get to execute the block at a time, but do you want to have your CPU spinning on the while block?