Sub topic 4
When Threads Share Data: Race Conditions
In the last chapter, you learned to start threads and wait for them with join. Each thread did its own work. Now we will look at what happens when two threads touch the same data at the same time. This is where many bugs in concurrent programs come from.
What Is Shared Mutable State?
Shared state is data that more than one thread can reach, such as a static field or a field on an object that two threads both use. Mutable means the data can change.
When data is shared but never changes, threads can read it safely. When data is shared and does change, threads can step on each other.
What Is a Race Condition?
A race condition is a bug where the result depends on the timing of threads. The threads "race" each other, and the order in which they run changes the answer. Since the timing differs from run to run, the bug can show up on one run and not on the next.
Why `count++` Is Not One Step
The line count++ looks like a single action. The computer actually does it in three steps:
- Read the current value of
count. - Add one to that value.
- Write the new value back to
count.
An operation is atomic when it happens as one step that no other thread can interrupt. count++ is not atomic. Another thread can run in the gap between the read and the write.
Both threads added one, but only one increment counted. This is called a lost update.
A Worked Example
The program below runs two threads. Each one adds 1 to a counter 100,000 times. We keep two counters. unsafeCount is a plain int. safeCount is an AtomicInteger, a class whose increment is atomic.
import java.util.concurrent.atomic.AtomicInteger;
public class CounterDemo {
private static int unsafeCount = 0;
private static final AtomicInteger safeCount = new AtomicInteger();
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> {
for (int i = 0; i < 100_000; i++) {
unsafeCount++;
safeCount.incrementAndGet();
}
};
Thread a = new Thread(work);
Thread b = new Thread(work);
a.start();
b.start();
a.join();
b.join();
System.out.println("unsafe: " + unsafeCount);
System.out.println("safe: " + safeCount.get());
}
}A typical run prints something like this:
unsafe: 137482
safe: 200000The right answer is 200,000. The plain counter usually comes up short because updates were lost. The atomic counter gets it right every time.
How to Spot a Race Condition
Ask these questions about any piece of data:
| Question | If the answer is yes |
|---|---|
| Can more than one thread reach this data? | It is shared. |
| Does any thread change it? | It is mutable. |
| Do reads and writes happen without protection? | There may be a race. |
Common risky patterns include:
x++,x--, orx += non a shared field.- "Check, then act" code, such as
if (list.isEmpty()) list.add(item);. - Using a plain
ArrayListorHashMapfrom several threads at once.
The next chapter shows how to protect shared state with synchronized, volatile, and atomic variables like AtomicInteger.
Exercise
Two threads each run total += 10; once on a shared int total that starts at 0. List the possible final values of total and explain why.
Show answer
The final value can be 20 or 10. If one thread finishes its read-add-write before the other starts, the result is 20. If both threads read 0 before either writes, both write 10, one update is lost, and the result is 10.
Exercise
Is a shared final String name that is never reassigned at risk of a race condition? Why or why not?
Show answer
No. The field is shared but not mutable. A String cannot change, and a final field cannot be reassigned, so every thread always reads the same value.