Atomic variables in Java provide a way to perform thread-safe operations on single variables without using explicit synchronization. They are part of the java.util.concurrent.atomic package and are widely used in high-performance, multi-threaded applications.
Common atomic classes provided by Java:
Atomic variables ensure visibility and atomicity without blocking other threads.
// Demonstrates AtomicInteger for thread-safe counting
import java.util.concurrent.atomic.AtomicInteger;
class AtomicDemo {
static AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) {
Runnable task = () -> {
for(int i = 0; i < 1000; i++) {
counter.incrementAndGet();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
}
}
Atomic variables rely on CAS. They only update memory if the value hasn't changed since you last read it.
Real value seen by all threads
Both threads increment the same AtomicInteger. The method incrementAndGet() guarantees that each increment is atomic, so no updates are lost, even without synchronized.
AtomicBoolean to control thread executionAtomicLongcompareAndSet() method