Sub topic 4
When Threads Share Data: Race Conditions
In earlier chapters you started threads, waited for them with join, and paused them with sleep. Each thread did its own work. Real programs often need threads to work on the same data, such as a shared counter, a list of orders, or a bank balance. This is where many concurrency bugs come from.
This chapter explains what goes wrong when threads share data. You will see a race condition happen, learn why it happens, and learn how to spot one in your own code. The next chapter covers the tools that fix it.
Key Terms
Here are the words this chapter uses.
- Shared state is data that more than one thread can reach. A
staticfield is a common example, because every thread in the program can read and change it. - Mutable means "can be changed." A variable you can assign a new value to is mutable.
- Shared mutable state is data that many threads can reach and that can change. This combination causes the trouble.
- A race condition is a bug where the result depends on the timing of threads. If the threads run in one order, the answer is right. If they run in another order, it is wrong.
- Interleaving is the order in which the steps of different threads are mixed together while they run.
- An atomic operation happens as one single step. No other thread can see it half-finished.
A Simple Line That Is Not Simple
Look at this line of Java:
count++;It looks like one step, but the computer does three steps:
- Read the current value of
countfrom memory. - Add one to that value.
- Write the new value back to memory.
When only one thread runs this code, the three steps always happen together. When two threads run it at the same time, the operating system can pause one thread between any two steps and let the other thread run. That pause is where the bug lives.
Watching an Update Get Lost
Suppose count is 5. Thread A and Thread B both want to add one, so the correct answer is 7. Here is one bad interleaving:
Both threads read 5 before either one wrote. Each thread then wrote 6. Thread B's write covered up Thread A's write. This is called a lost update. Nothing crashed and no error was printed. The answer was simply wrong.
Seeing the Race in Real Code
The program below starts two threads. Each thread adds one to a counter 100,000 times. If everything worked, the final count would be 200,000.
The program uses two counters. unsafeCount is a plain int. safeCount is an AtomicInteger, a class from java.util.concurrent.atomic whose incrementAndGet method does the read, add, and write as one atomic step.
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());
}
}Save it as CounterDemo.java, then compile and run it:
javac CounterDemo.java
java CounterDemoA typical run prints something like this:
unsafe: 137492
safe: 200000Your unsafe number will be different. Run the program several times and it will probably change each time. Sometimes it may even be exactly 200,000. The safe number is always 200,000.
Here is what happened:
- Both threads ran
unsafeCount++at the same time. Many increments were lost, just as in the diagram. incrementAndGetcannot be split by another thread, so no increment onsafeCountwas lost.- The calls to
joinmatter. Without them,mainmight print the counters before the threads finish. That would be a different bug.
Why the Result Changes Every Run
The result changes because you do not control when a thread runs. A part of the operating system called the scheduler decides which thread runs on which CPU core, and for how long. It makes these choices based on many things, such as other programs running and how many cores your computer has.
So the interleaving is different on every run. A program whose output can change from run to run, even with the same input, is called nondeterministic. Race conditions make programs nondeterministic, which makes them hard to find and hard to repeat.
A Second Kind of Race: Check-Then-Act
Lost updates are one kind of race. Another common kind is check-then-act. The code checks a condition, then acts on it. Between the check and the action, another thread changes the data.
In this example, a concert has one ticket left. Two buyers try to buy it at the same time.
public class TicketDemo {
private static int ticketsLeft = 1;
public static void main(String[] args) throws InterruptedException {
Runnable buyer = () -> {
if (ticketsLeft > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
ticketsLeft--;
System.out.println(Thread.currentThread().getName() + " bought a ticket");
}
};
Thread alice = new Thread(buyer, "alice");
Thread bob = new Thread(buyer, "bob");
alice.start();
bob.start();
alice.join();
bob.join();
System.out.println("Tickets left: " + ticketsLeft);
}
}A typical run prints:
alice bought a ticket
bob bought a ticket
Tickets left: -1The order of the first two lines may change. The steps are:
- Alice checks
ticketsLeft > 0. It is 1, so the check passes. - Bob checks
ticketsLeft > 0. It is still 1, so his check passes too. - Both threads take one away. The count goes to -1, and one ticket was sold twice.
The Thread.sleep(10) makes the gap between "check" and "act" wider, so you can see the bug every time. In real code the gap is much shorter, but it is still there. A shorter gap means the bug happens less often, not that it never happens.
A Third Problem: Visibility
There is one more problem with shared data. To run fast, each CPU core keeps its own copy of some data in a small, quick memory called a cache. Java may also reorder or reuse values in ways that are fine for one thread. As a result, one thread can change a variable and another thread may not see the change, sometimes for a long time.
This is called a visibility problem. It can happen even when only one thread writes and the other only reads. For example, one thread sets a boolean running = false to ask a loop in another thread to stop, and the loop keeps running because it never sees the new value.
You do not need to fix this yet. Just remember that sharing data between threads has two separate risks:
| Risk | What goes wrong | Example |
|---|---|---|
| Lost update | Two threads change a value and one change disappears | Two `count++` calls only add 1 |
| Check-then-act | Data changes between a check and an action | Two buyers get the last ticket |
| Visibility | One thread never sees another thread's change | A stop flag is ignored |
The next chapter shows how synchronized, volatile, and atomic classes like AtomicInteger handle each of these risks.
How to Spot a Race Condition
When you read multithreaded code, ask these questions about each variable:
Some common places where shared mutable state hides:
staticfields, which every thread can reach.- Fields of one object that is passed to several threads, such as one
Runnablegiven to twoThreadobjects. InCounterDemo, both threads ran the sameworklambda and changed the samestaticfields. - Normal collections like
ArrayListandHashMap. They are not built for threads. Adding to them from two threads at once can lose items or damage the collection's internal structure.
Local variables declared inside a method or lambda are safe. Each thread gets its own copy. In CounterDemo, the loop variable i is local, so each thread has its own i and they never interfere.
Summary
- Shared mutable state is data that several threads can reach and change.
- Operations like
count++are really three steps: read, add, write. Another thread can run between them. - A race condition makes the result depend on thread timing, so the output can change from run to run.
- Lost updates, check-then-act bugs, and visibility problems are the three main risks.
- Local variables and data that never changes are safe to use from many threads.
Exercise
Two threads each run total = total + 5; once on a shared int total that starts at 10. What results are possible, and why?
Show answer
The result can be 20 or 15. If one thread finishes its read, add, and write before the other reads, the second thread reads 15 and writes 20. If both threads read 10 before either writes, both compute 15 and both write 15, so one update is lost.
Exercise
In CounterDemo, the loop variable i is used by both threads, but it never causes a race. Why not?
Show answer
i is a local variable declared inside the lambda. Each thread that runs the lambda gets its own separate copy of i on its own stack, so no data is shared between the threads.
Exercise
A method contains if (!names.contains(name)) { names.add(name); }, where names is an ArrayList shared by many threads. Name the two kinds of problem in this code.
Show answer
First, it is a check-then-act race: two threads can both see that the name is missing and both add it, which creates a duplicate. Second, ArrayList is not safe for use by several threads, so two add calls running at the same time can lose an element or damage the list's internal state.
Exercise
You run TicketDemo without the Thread.sleep(10) call and it prints "Tickets left: 0" ten times in a row. Is the race fixed?
Show answer
No. Removing the sleep only makes the gap between the check and the decrement smaller, so the bad interleaving happens less often. Both threads can still pass the check before either one decrements. The code needs real protection, which the next chapter covers.