Sub topic 4
Atomicity: Why count++ Is Not One Step
In the last chapter, two threads added to the same counter, and the total came out wrong. This chapter explains why. The short answer is that count++ looks like one step but is really three. When another thread can cut in between those steps, updates get lost.
What "atomic" means
An operation is a piece of work the program does, such as reading a variable or adding two numbers.
An atomic operation is one that happens all at once, as a single step. No other thread can see it half done. No other thread can slip in during the middle of it. The word comes from the old idea of an atom as something that cannot be split.
A compound action is a group of steps that you want to act as one unit, but that the computer actually runs as several separate steps.
The core problem in this chapter is simple. Many lines of Java look atomic but are really compound actions.
Breaking count++ apart
When you write count++, the computer does three things:
- Read: load the current value of
countfrom memory. - Modify: add 1 to that value.
- Write: store the new value back into
count.
This pattern is called read-modify-write. You can write the same three steps out by hand. This program does exactly what count++ does, just more visibly:
public class ExpandedIncrement {
private static int count = 0;
public static void main(String[] args) {
int temp = count; // step 1: read
temp = temp + 1; // step 2: modify
count = temp; // step 3: write
System.out.println(count);
}
}It prints 1. With one thread, the three steps always run in order, so nothing goes wrong. The trouble starts when a second thread runs the same three steps at the same time.
Seeing the steps in bytecode
Java source code is turned into bytecode, which is a list of simple instructions that the Java Virtual Machine (JVM) runs. You can view bytecode with the javap tool that comes with the JDK:
javac ExpandedIncrement.java
javap -c ExpandedIncrementFor a static field count, the line count++ compiles to four instructions like these:
getstatic #7 // Field count:I (read the value)
iconst_1 // (push the number 1)
iadd // (add them)
putstatic #7 // Field count:I (write the result back)The read happens at getstatic, and the write happens at putstatic, and those are separate instructions. A thread can be paused between any two of them. The operating system decides when each thread runs. It can stop a thread at any instruction and let another one run.
How an update gets lost
Suppose count is 5, and two threads, T1 and T2, both run count++. Here is one possible order of events:
| Step | Thread T1 | Thread T2 | count in memory |
|---|---|---|---|
| 1 | reads 5 | 5 | |
| 2 | reads 5 | 5 | |
| 3 | adds 1, gets 6 | 5 | |
| 4 | adds 1, gets 6 | 5 | |
| 5 | writes 6 | 6 | |
| 6 | writes 6 | 6 |
Two increments ran, so the answer should be 7. It is 6. T2 read the old value before T1 wrote its new one, so T2's write covered up T1's work. This is called a lost update.
Interleavings like this are rare on any single increment. But the race demo from the last chapter runs 200,000 increments. Even a rare overlap happens many times across that many tries, so the total usually comes out short.
Other compound actions
Read-modify-write is one common kind of compound action. Check-then-act is another. In check-then-act, a thread checks a condition and then acts based on it. Between the check and the action, another thread can change the condition.
Here is a classic example, lazy initialization. That means creating an object only the first time someone asks for it:
public class LazyHolder {
private static StringBuilder instance;
public static StringBuilder getInstance() {
if (instance == null) { // check
instance = new StringBuilder(); // act
}
return instance;
}
public static void main(String[] args) {
System.out.println(getInstance() == getInstance());
}
}On one thread, this prints true. With two threads, both can see instance == null before either one assigns it. Then each creates its own object, and the two callers end up holding different objects.
| Kind of compound action | Example | What can go wrong |
|---|---|---|
| Read-modify-write | `count++`, `total += x` | Two threads read the same old value; one update is lost |
| Check-then-act | `if (x == null) x = new ...` | Two threads both pass the check and both act |
| Check-then-act on a map | `if (!map.containsKey(k)) map.put(k, v)` | Two threads both insert, and one value overwrites the other |
| Multi-field update | changing `x` and `y` together | Another thread sees the new `x` with the old `y` |
What is atomic in Java
Some single operations are atomic by themselves:
- Reading or writing a field of type
int,short,byte,char,boolean, orfloat. - Reading or writing an object reference.
But being atomic alone does not make a sequence of them atomic. Each read is atomic, and each write is atomic, but "read, then write" is not.
Here are a few other lines that look like one step but are compound:
count += 5is a read, an add, and a write.--countis a read, a subtract, and a write.x = ywith two shared fields readsy, then writesx.
How to make a compound action atomic
To fix a compound action, you must make its steps run as one unit. While one thread is inside that unit, no other thread can enter it. Later chapters cover the tools in detail:
synchronizedmethods and blocks let only one thread at a time run the guarded code.- Atomic classes such as
AtomicIntegerdo the whole read-modify-write in a single atomic operation. - Concurrent collections such as
ConcurrentHashMapoffer atomic methods likemergeandputIfAbsentthat replace check-then-act code.
Atomicity is only half the story. Even a single write can be invisible to another thread for a while. That is the visibility problem, which is the subject of the next chapter.
Exercise
Name the three steps that make up count++, and explain in one or two sentences how two threads can lose an update.
Show answer
The steps are read the current value, add 1, and write the result back. If both threads read the same old value before either writes, both compute the same new value, and the second write overwrites the first, so one increment disappears.
Exercise
Is this method safe when many threads call it at the same time? Why or why not? void withdraw(int amt) { if (balance >= amt) { balance = balance - amt; } }
Show answer
It is not safe. It contains two compound actions: a check-then-act (checking balance, then withdrawing) and a read-modify-write (balance - amt). Two threads can both pass the check with the same balance and both withdraw, which can overdraw the account or lose one of the updates.
Exercise
Writing to an int field is atomic. Does that make count = count + 1 atomic? Explain.
Show answer
No. The single write is atomic, and the single read is atomic, but the line performs a read, then an add, then a write. Another thread can run between the read and the write, so the line as a whole is a compound action.
Exercise
Why can a plain long field be a problem even if a thread only ever writes it, never increments it?
Show answer
The Java rules allow the JVM to write a non-volatile long as two 32-bit halves. A reader on another thread might see one half from the old value and one half from the new value, a "torn" value that no thread ever wrote. Declaring the field volatile makes its single reads and writes atomic.