Sub topic 10
Atomic Variables: AtomicInteger and Friends
In earlier chapters you fixed a broken counter with synchronized. That works, but it is heavy for a job as small as adding one to a number. Java has a lighter tool for this. It lives in the package java.util.concurrent.atomic, and its most used class is AtomicInteger.
This chapter shows what atomic variables are, how they work, and where they stop being enough.
What an Atomic Variable Is
An atomic variable is an object that holds one value and changes it in a single step that cannot be split. No other thread can see the value halfway through a change.
Recall the problem with count++. It is really three steps:
- Read
count. - Add one.
- Write the result back.
Two threads can both read the same old value. Both add one. Both write. One increment is lost.
An AtomicInteger gives you methods that do all three steps as one. It also makes each new value visible to all other threads right away, just like a volatile field does. So it solves both problems from earlier chapters: atomicity and visibility.
A Counter Without a Lock
Here is a counter built on AtomicInteger:
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();
}
}There is no synchronized keyword and no lock object. The method incrementAndGet adds one and returns the new value as one atomic step. The method get reads the current value, and it always sees the latest write.
The field is final. That means the field always points to the same AtomicInteger object. The number inside the object still changes. Making the field final stops anyone from swapping in a different counter object by mistake.
Fixing the Race Demo
Now take the race demo from the Race Conditions chapter and switch it to an atomic counter. Save this as AtomicRaceDemo.java and run it.
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicRaceDemo {
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());
}
}This prints 200000 every time. The plain int version often printed less.
The Most Useful Methods
AtomicInteger has many methods. These are the ones you will use most.
| Method | What it does | Returns |
|---|---|---|
| `get()` | Reads the value | Current value |
| `set(v)` | Writes a new value | Nothing |
| `incrementAndGet()` | Adds 1 | New value |
| `getAndIncrement()` | Adds 1 | Old value |
| `addAndGet(n)` | Adds `n` | New value |
| `compareAndSet(expect, update)` | Sets `update` only if the value equals `expect` | `true` if it changed |
| `updateAndGet(fn)` | Applies a function to the value | New value |
Watch the names. incrementAndGet acts like ++count: change first, then return. getAndIncrement acts like count++: return the old value, then change. Mixing these up is a common off-by-one bug.
How It Works Inside: Compare-and-Set
How can a class be safe without a lock? The answer is a special instruction that the processor provides, called compare-and-set (CAS).
CAS takes three things: a memory location, the value you expect to find there, and the new value you want. In one step that cannot be split, the processor checks whether the location still holds the expected value. If it does, the processor writes the new value and reports success. If another thread changed it first, nothing is written and CAS reports failure.
When CAS fails, the code just tries again with the fresh value. This is called a CAS loop.
No thread ever blocks or waits for a lock. A thread that loses the race simply retries. This is why atomic classes are often faster than locks when the work is tiny.
Writing Your Own CAS Loop
You can use compareAndSet yourself. Here is a class that tracks the highest value ever seen across many threads:
import java.util.concurrent.atomic.AtomicInteger;
public class MaxTracker {
private final AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);
public void offer(int value) {
while (true) {
int current = max.get();
if (value <= current) {
return;
}
if (max.compareAndSet(current, value)) {
return;
}
// another thread changed max; loop and try again
}
}
public int get() {
return max.get();
}
public static void main(String[] args) {
MaxTracker tracker = new MaxTracker();
tracker.offer(5);
tracker.offer(12);
tracker.offer(7);
System.out.println(tracker.get()); // prints 12
}
}Most of the time you do not need to write the loop by hand. updateAndGet runs the same loop for you:
import java.util.concurrent.atomic.AtomicInteger;
public class MaxTrackerShort {
private final AtomicInteger max = new AtomicInteger(Integer.MIN_VALUE);
public void offer(int value) {
max.updateAndGet(current -> Math.max(current, value));
}
public int get() {
return max.get();
}
}The Friends: Other Atomic Classes
The package has a class for each common kind of value.
| Class | Holds | Typical use |
|---|---|---|
| `AtomicInteger` | an `int` | counters, IDs |
| `AtomicLong` | a `long` | large counters, byte totals |
| `AtomicBoolean` | a `boolean` | "do this only once" flags |
| `AtomicReference<V>` | an object reference | swapping a whole object safely |
| `LongAdder` | a sum of `long` values | counters updated by many threads at once |
AtomicBoolean is handy for making sure something runs exactly once:
import java.util.concurrent.atomic.AtomicBoolean;
public class OneTimeInit {
private final AtomicBoolean started = new AtomicBoolean(false);
public void start() {
if (started.compareAndSet(false, true)) {
System.out.println("Starting up");
}
}
public static void main(String[] args) {
OneTimeInit init = new OneTimeInit();
init.start(); // prints "Starting up"
init.start(); // prints nothing
}
}Only the first caller sees false and swaps it to true. Every later caller fails the CAS and skips the work.
LongAdder deserves a note. When many threads hit one AtomicLong very hard, CAS keeps failing and threads spend time retrying. LongAdder spreads the count across several internal cells and adds them up when you call sum(). It is faster for heavy write traffic. The catch is that sum() is not an exact snapshot while updates are still running, so use it for statistics, not for values that decide program logic.
Where Atomic Variables Fall Short
Each single method call is atomic. A sequence of calls is not.
This code is broken:
import java.util.concurrent.atomic.AtomicInteger;
public class BrokenLimit {
private final AtomicInteger seats = new AtomicInteger(10);
public boolean book() {
if (seats.get() > 0) { // check
seats.decrementAndGet(); // act
return true;
}
return false;
}
}Two threads can both see 1, both pass the check, and both decrement. The seat count drops to -1. This is a check-then-act race, the same kind you met with plain fields. The fix is to fold the check and the change into one CAS:
import java.util.concurrent.atomic.AtomicInteger;
public class SafeLimit {
private final AtomicInteger seats = new AtomicInteger(10);
public boolean book() {
while (true) {
int current = seats.get();
if (current == 0) {
return false;
}
if (seats.compareAndSet(current, current - 1)) {
return true;
}
}
}
}A second limit: two atomic variables are not atomic together. If a low and a high value must always satisfy low <= high, updating them as two separate AtomicIntegers lets another thread see a bad pair in between. For rules that involve more than one variable, use a lock, or put both values in one immutable object held by an AtomicReference.
One more edge case: atomic integers overflow just like int. Calling incrementAndGet on Integer.MAX_VALUE wraps to Integer.MIN_VALUE with no error. Use AtomicLong if a counter might grow very large.
Exercises
Exercise
A thread calls getAndIncrement() on an AtomicInteger that holds 4. What does the call return, and what value does the AtomicInteger hold afterward?
Show answer
It returns 4, the old value, and the AtomicInteger then holds 5. incrementAndGet() would have returned 5.
Exercise
Why is "if (counter.get() < 100) counter.incrementAndGet();" not thread-safe, even though counter is an AtomicInteger?
Show answer
Each call is atomic on its own, but the check and the increment are two separate steps. Two threads can both read 99, both pass the check, and both increment, so the counter reaches 101. Combine the check and the update in a compareAndSet loop, or use updateAndGet(v -> v < 100 ? v + 1 : v).
Exercise
You pass a lambda to updateAndGet that prints a log line each time it runs. Under heavy load you see more log lines than updates. Why?
Show answer
updateAndGet uses a CAS loop. When another thread changes the value first, the CAS fails and the lambda runs again with the new value. The lambda can run several times for one successful update, so it should have no side effects.
Exercise
Ten threads each add to a shared hit counter millions of times per second, and you only read the total once a minute for a report. Which class fits best, and why?
Show answer
LongAdder. It spreads updates across internal cells so threads rarely fight over the same value, which makes writes faster than with AtomicLong. The total from sum() is only approximate while updates are still running, and that is fine for a periodic report.