Sub topic 3
Race Conditions: When Two Threads Collide
In the last chapter you saw that shared mutable state is data that more than one thread can read and change. This chapter shows what goes wrong when two threads change that data at the same time.
What Is a Race Condition?
A race condition is a bug where the result depends on timing. Two threads "race" to use the same data. Sometimes one wins and sometimes the other wins. The program gives different answers on different runs.
Race conditions are hard to find. Your code may work a hundred times and then fail once. The failure might never show up on your laptop, then show up on a busy server.
A Worked Example
Here, two threads each add 1 to a shared counter 100,000 times. You would expect the total to be 200,000.
public class RaceDemo {
private static int count = 0;
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
count++;
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(count);
}
}Run it a few times. You will often see numbers like 137,412 or 158,903. Each run can print a different number.
Why Updates Get Lost
The line count++ looks like one step. It is really three:
- Read the current value of
count. - Add 1 to it.
- Write the new value back.
A thread can be paused between any of these steps. If both threads read the same value before either one writes, one update is lost. This is called a lost update.
Each thread did its work correctly. The bug comes from how their steps were mixed together. This mixing is called interleaving: the order in which steps from different threads happen to run.
What Makes a Race Possible
A race condition needs all three of these:
| Ingredient | In the example |
|---|---|
| More than one thread | `t1` and `t2` |
| Shared data | The static field `count` |
| At least one thread writes | Both threads run `count++` |
Remove any one of them and this race cannot happen. If only one thread runs, or each thread has its own counter, or the data never changes, the result is always correct.
The next chapters look at the two causes behind races. The first is atomicity, which is why count++ can be split apart. The second is visibility, which is about whether one thread can see another thread's write at all.
Exercise
In RaceDemo, why does the program sometimes print a number less than 200000 instead of exactly 200000?
Show answer
Because count++ is three steps: read, add, write. Both threads can read the same value before either writes it back, so one thread's write replaces the other's and an increment is lost.
Exercise
Name the three ingredients a race condition needs, and give one way to remove one of them from RaceDemo.
Show answer
Multiple threads, shared data, and at least one thread writing. You could remove one by giving each thread its own local counter and adding the two results after both threads finish with join().