Synchronization and locks · Topic 4 of 8
Atomic variables
Definition​
Atomic classes such as AtomicInteger update one value safely without a lock, using a hardware instruction called compare-and-swap. LongAdder is even faster when many threads only add to a counter.
Example code​
Counting from many threads without locks
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
class Demo {
public static void main(String[] args) throws InterruptedException {
AtomicInteger counter = new AtomicInteger();
LongAdder adder = new LongAdder();
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
counter.incrementAndGet(); // atomic
adder.increment(); // atomic, scales better under heavy contention
}
};
Thread a = new Thread(work), b = new Thread(work);
a.start(); b.start();
a.join(); b.join();
System.out.println(counter.get() + " " + adder.sum());
AtomicInteger stock = new AtomicInteger(5);
System.out.println(stock.compareAndSet(5, 4)); // only changes it if it is still 5
System.out.println(stock.compareAndSet(5, 3)); // fails: the value is now 4
}
}
// Output:
// 200000 200000
// true
// false
Finished this page? Track your progress (saved only in your browser).