Sub topic 3
Race Conditions: When Two Threads Collide
In the last chapter, you saw that some data is both shared (more than one thread can reach it) and mutable (it can change). This chapter shows what goes wrong when two threads change that data at the same time. That problem is called a race condition. It is the most common bug in concurrent code, so learning to spot it is the first step toward writing safe programs.
What Is a Race Condition?
A race condition is a bug where the result of a program depends on the timing of threads. If one thread happens to run a little faster or slower, you get a different answer.
The name comes from the idea of two runners racing to the same spot. Whoever gets there first decides what happens. In a program, the "spot" is a piece of shared data, like a field or a list.
A race condition needs three things:
- Two or more threads.
- Shared data that at least one thread changes.
- No rule that stops the threads from getting in each other's way.
Take away any one of these, and the race goes away. Later chapters show how to take each one away.
A Program That Gets the Wrong Answer
Here is a small program. Two threads each add 1 to a shared counter 100,000 times. You would expect the final 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);
}
}Save this as RaceDemo.java, then compile and run it:
javac RaceDemo.java
java RaceDemoRun it several times. You will likely see numbers like these:
| Run | Printed value |
|---|---|
| 1 | 137492 |
| 2 | 200000 |
| 3 | 158811 |
| 4 | 171206 |
Your numbers will differ. The point is that they change from run to run, and most are less than 200,000. The code has no syntax errors and throws no exceptions, yet it is wrong.
Why Updates Get Lost
The line count++ looks like one action. To the computer it is actually three small steps:
- Read the current value of
count. - Add 1 to that value.
- Write the new value back to
count.
The next chapter looks at this in detail. For now, the key idea is that another thread can sneak in between these steps.
Imagine count is 5. Here is one bad timing:
Both threads did their work. But Thread 2 wrote its answer on top of Thread 1's answer. One increment vanished. This is called a lost update: a change that one thread made is overwritten by another thread that never saw it.
Each time this happens, the total drops by one. Over 200,000 increments, it can happen thousands of times.
Interleaving: The Order Is Not Fixed
Interleaving is the order in which the steps of different threads actually run. The operating system's scheduler is the part of the system that decides which thread runs, and when. It can pause a thread at almost any point and run another one.
You do not control the scheduler. It depends on how many CPU cores you have, what else the computer is doing, and other factors. So the interleaving is different on every run. Sometimes the threads take turns cleanly and you get 200,000. Often they overlap and you lose updates.
This is why race conditions are hard to find:
- The program may pass a test on your laptop and fail on a server.
- Adding a
System.out.printlnto debug can change the timing and hide the bug. - The bug may show up once a week in production and never in testing.
Another Kind of Race: Check-Then-Act
Lost updates are one type of race. Another common type is check-then-act. A thread checks a condition, then acts based on what it saw. But another thread can change things between the check and the act.
Here is a bank account example:
public class Account {
private int balance = 100;
public void withdraw(int amount) {
if (balance >= amount) { // check
balance = balance - amount; // act
}
}
public int getBalance() {
return balance;
}
public static void main(String[] args) throws InterruptedException {
Account account = new Account();
Thread t1 = new Thread(() -> account.withdraw(80));
Thread t2 = new Thread(() -> account.withdraw(80));
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(account.getBalance());
}
}The rule says you cannot withdraw more than you have. With 100 in the account, only one 80 withdrawal should succeed, leaving 20.
But both threads can run the check balance >= 80 while the balance is still 100. Both see true. Both subtract 80. The balance becomes -60, or some other wrong value. The check was correct when it ran, but it was stale by the time the act happened.
With only one withdrawal per thread, this window is tiny, so you may see 20 almost every time. The bug is still there. It just shows up rarely, which makes it more dangerous.
Comparing the Two Patterns
| Pattern | What happens | Example |
|---|---|---|
| Read-modify-write | Two threads read the same old value and both write a new one. One update is lost. | `count++` |
| Check-then-act | A thread decides based on a check, but the data changes before it acts. | `if (balance >= amount) balance -= amount;` |
Both patterns have the same root cause. A group of steps that should happen as one unit can be split up by another thread.
When There Is No Race
Not every multithreaded program has a race. These cases are safe:
- Each thread has its own data. If each thread uses a local variable, no other thread can touch it.
- The data never changes. If threads only read a value that was set before they started, there is nothing to collide over.
- Access is protected. If a lock or a special class makes the steps happen as one unit, threads cannot interleave inside them.
The rest of this tutorial covers these three approaches. Synchronized methods, atomic classes, and locks protect access. Immutable objects stop the data from changing. Thread confinement keeps each thread's data private.
Summary
- A race condition is a bug where the result depends on thread timing.
count++is really read, add, write, so two threads can lose an update.- Check-then-act code can act on information that is already out of date.
- The scheduler picks the interleaving, so race bugs appear randomly and are hard to reproduce.
- Getting the right answer once does not prove the code is safe.
Exercise
In RaceDemo, why is the printed total usually less than 200000 and never more?
Show answer
Each count++ reads, adds 1, and writes back. When two threads read the same value, both write the same result, so one increment is lost. Overlaps can only throw increments away. They can never add extra ones, so the total can only be 200000 or lower.
Exercise
A developer runs RaceDemo once, sees 200000, and says the code is correct. What is wrong with this reasoning?
Show answer
Thread interleaving changes on every run. A single correct result may only mean the threads did not overlap that time. The code has no protection for count, so it can still lose updates on other runs or other machines.
Exercise
Is this method safe if two threads call it at the same time on the same object? if (list.isEmpty()) { list.add("first"); }
Show answer
No. This is a check-then-act race. Both threads can see that the list is empty before either one adds an item. Both then add "first", so the list ends up with two items instead of one.
Exercise
Two threads each run a loop that increments a local variable declared inside the lambda, like int local = 0; local++;. Is there a race condition? Why or why not?
Show answer
No. Each thread gets its own copy of a local variable, so the data is not shared. Without shared mutable data, there is nothing for the threads to collide over.