Race Conditions
in Java
Understand why concurrent threads accessing shared state can produce unpredictable results, and learn to recognize the patterns that cause them.
What Is Concurrency?
Modern programs often run multiple threads at the same time. Each thread is an independent path of execution that can read and write to the same variables in memory. When two or more threads operate on shared data simultaneously, their operations can overlap in unexpected ways.
Defining a Race Condition
A race condition occurs when the correctness of a program depends on the relative timing of two or more threads. The "race" is between threads to read and write shared data: whoever gets there first determines the outcome.
Why Race Conditions Matter
Race conditions are among the hardest bugs to find because they are non-deterministic: the same code can produce different results on different runs. They cause real-world failures in banking software, web servers, and embedded systems.
The Core Rule
All three conditions must be true simultaneously. Remove any one, and the race condition disappears:
The Read-Modify-Write Pattern
The most common race condition: an operation like count++ looks atomic but actually involves three separate steps. If a thread is interrupted between steps, another thread can interfere.
Check-Then-Act Pattern
Another classic race: a thread checks a condition, then acts based on the result. Between the check and the act, another thread can change the state, making the original check invalid.
Race Condition vs. Data Race
These terms are related but not the same. Understanding the distinction helps you reason about what exactly is going wrong in concurrent code.
| Race Condition | Data Race | |
|---|---|---|
| Definition | Correctness depends on thread timing | Unsynchronized concurrent access to same memory |
| Scope | Logical / semantic level | Memory / hardware level |
| Can exist alone? | Yes: race with proper memory access but wrong logic | Yes: data race without incorrect logic |
| Example | Check-then-act on a ConcurrentHashMap | Two threads writing count with no volatile / lock |
| Fix | Atomic compound operations | synchronized, volatile, Atomic types |
How to Spot a Race Condition
synchronized block, Lock, or Atomic variable protecting the compound action?Example 1: Unsafe Counter
Fixing the Counter: Three Approaches
synchronizedAtomicIntegerAtomicInteger.incrementAndGet(): hardware-level atomic operation, no lock needed.ReentrantLockExample 2: Lazy Initialization
Example 3: Compound Map Operation
Each individual operation (get and put) is thread-safe, but the combination is not. The gap between get and put is where another thread can interfere.
The Visibility Problem
Even a single write can cause issues. Without the volatile keyword or synchronization, changes made by one thread may never become visible to another thread due to CPU caching.
Common Mistakes
ConcurrentHashMap makes individual ops atomic, but compound operations (get then put) are still unsafe.Summary of Race Condition Patterns
| Pattern | Danger | Fix |
|---|---|---|
| Read-Modify-Write | Lost updates (e.g., count++) |
AtomicInteger or synchronized |
| Check-Then-Act | Stale condition (e.g., lazy init) | synchronized block around both |
| Compound Map Op | Lost increment on map values | merge() or compute() |
| Visibility | Thread never sees updated flag | volatile keyword |
Question 1 of 5
Two threads execute count++ on a shared int count = 0 without synchronization. Which of the following is a possible final value of count?
0 before either writes, both write 1, and one increment is lost. The final value of 1 is possible (as is 2, but not 0, 3, or -1).Question 2 of 5
Which three conditions must all be true for a race condition to exist?
Question 3 of 5
Code snippet:
ConcurrentHashMap<String, Integer> map = ...;
// Thread A and Thread B both run:
Integer val = map.get("k");
if (val != null) {
map.put("k", val + 1);
}
What type of race condition is present in this code?
ConcurrentHashMap only makes individual methods atomic, not compound sequences. Use map.merge() or map.compute() instead.Question 4 of 5
A thread sets boolean running = false, but another thread looping on while (running) never exits. What is the most likely cause?
volatile or synchronization, the reading thread's CPU core may keep reading a cached copy of running that still says true. Declaring the field volatile forces reads from main memory.Question 5 of 5
Which of the following scenarios is free from race conditions?