Sub topic 10
Atomic Variables: AtomicInteger and Friends
Why We Need Them
You have seen that count++ is not one step. It reads the value, adds one, and writes it back. Two threads can mix up those steps and lose updates. A synchronized method fixes this, but it uses a lock for one tiny operation.
Java offers a lighter tool. An atomic variable is an object that holds a value and changes it in one step that no other thread can break into. You can find these classes in the package java.util.concurrent.atomic.
Meet AtomicInteger
AtomicInteger is an atomic variable that holds an int. Its method incrementAndGet() adds one and returns the new value, all as a single atomic action. An atomic action is one that happens completely or not at all, so other threads never see it half done.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicCounter {
private final AtomicInteger count = new AtomicInteger();
public int increment() {
return count.incrementAndGet();
}
public int get() {
return count.get();
}
}This class has no synchronized keyword and no lock, and it is still thread-safe. Atomic variables also give you the same visibility as volatile, so get() always sees the latest value.
A Worked Example
Here is the race demo again, now with AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
private static final AtomicInteger count = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count.incrementAndGet();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count.get());
}
}It prints 200000 every time.
How It Works Inside
Atomic classes use a CPU instruction called compare-and-set (CAS). CAS means "set the value to X, but only if it still equals Y." If another thread changed the value first, CAS fails, and the method tries again with the fresh value.
The Friends
| Class | Holds | Useful methods |
|---|---|---|
| `AtomicInteger` | `int` | `incrementAndGet`, `addAndGet`, `compareAndSet` |
| `AtomicLong` | `long` | same as `AtomicInteger` |
| `AtomicBoolean` | `boolean` | `get`, `set`, `compareAndSet` |
| `AtomicReference<V>` | an object reference | `get`, `set`, `compareAndSet`, `updateAndGet` |
When to Use Them
Use an atomic variable when your shared state is one value, like a counter or a flag. If you must keep two or more values in step with each other, use a lock instead.
Exercise
A thread runs if (count.get() < 10) { count.incrementAndGet(); } where count is an AtomicInteger. Several threads run this code at once. Can count go above 10? Why?
Show answer
Yes. The check and the increment are two separate atomic actions. Several threads can all see 9, pass the check, and then all increment. One fix is a single atomic call: count.updateAndGet(v -> v < 10 ? v + 1 : v);.
Exercise
You need to track a total of bytes downloaded that may exceed about 2.1 billion. Which atomic class should you use, and which method adds a chunk size to it?
Show answer
Use AtomicLong, because an int overflows past 2,147,483,647. Call total.addAndGet(chunkSize).