Senior
Code task: AtomicBoolean and race condition (screenshot with code)
sobes.tech AI
Answer from AI
In Java, the AtomicBoolean class provides atomic operations on a boolean value, which helps prevent race conditions when accessed from multiple threads.
A race condition occurs when several threads read and modify shared state simultaneously without synchronization, leading to unpredictable results.
Using AtomicBoolean allows performing operations like compareAndSet, getAndSet, and others atomically, without the need to explicitly use synchronized or locks.
Example:
import java.util.concurrent.atomic.AtomicBoolean;
public class Example {
private AtomicBoolean flag = new AtomicBoolean(false);
public void doOnce() {
if (flag.compareAndSet(false, true)) {
// This block will only execute once
System.out.println("Performing action once");
}
}
}
Here, compareAndSet guarantees that only one thread can change the value from false to true and execute the code inside the if, preventing a race condition when trying to perform the action multiple times.