Sub topic 4
Atomicity: Why count++ Is Not One Step
In the last chapter, two threads added to the same counter, and the total often came out too low. This chapter explains why. The cause is a property called atomicity.
What Atomicity Means
An atomic action is one that happens all at once. No other thread can see it half done. It either has not started or it has fully finished.
A compound action is an action made of several smaller steps. If another thread can step in between those steps, the compound action is not atomic.
count++ Hides Three Steps
The line count++ looks like one step, but the computer does three:
- Read: load the current value of
count. - Modify: add 1 to that value.
- Write: store the new value back into
count.
This pattern is called read-modify-write. The program below spells out the three steps so you can see them:
public class ThreeSteps {
private static int count = 0;
public static void main(String[] args) {
int temp = count; // 1. read
temp = temp + 1; // 2. modify
count = temp; // 3. write
System.out.println(count); // prints 1
}
}On one thread this works fine. With two threads it can break.
How an Update Gets Lost
Say count is 5. Thread A reads 5. Before A writes, Thread B also reads 5. Both add 1 and get 6. Both write 6. Two increments happened, but count only went up by one. This is called a lost update.
The thread scheduler decides when each thread runs, and it can pause a thread between any two steps. That is why the result changes from run to run.
Check-Then-Act: Another Compound Action
Read-modify-write is one kind of compound action. Another is check-then-act: you test a condition, then act on it.
if (!map.containsKey(key)) { // check
map.put(key, value); // act
}Between the check and the act, another thread may add the same key. Both threads then believe the key was missing.
What Fixes It
To make a compound action safe, you must make it atomic, so no other thread can step in partway. Later chapters show the tools for this: synchronized, atomic classes such as AtomicInteger, and concurrent collections.
Exercise
Two threads each run count++ once. count starts at 10. What final values are possible, and why?
Show answer
12 or 11. If one thread finishes all three steps before the other reads, the result is 12. If both read 10 before either writes, both write 11 and one update is lost.
Exercise
Is balance = balance - amount; atomic? Name the kind of compound action.
Show answer
No. It reads balance, subtracts amount, and writes the result back. It is a read-modify-write action.