01 / 21

Race Conditions
in Java

Understand why concurrent threads accessing shared state can produce unpredictable results, and learn to recognize the patterns that cause them.

Java Concurrency

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.

Thread A Thread B Shared State count = 5 read / write read / write

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.

Shared State
A variable, object, or resource accessible by more than one thread.
Non-Atomic Operation
An operation that takes multiple steps (read, modify, write) and can be interrupted between steps.
Data Race
Two threads access the same memory location with no synchronization and at least one is a write.

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.

1
Intermittent failures: bugs appear and disappear depending on CPU scheduling, making them nearly impossible to reproduce reliably.
2
Data corruption: shared variables can end up with values that no single thread intended.
3
Security vulnerabilities: attackers can exploit race conditions to bypass checks (e.g., TOCTOU attacks).

The Core Rule

All three conditions must be true simultaneously. Remove any one, and the race condition disappears:

1
No shared state: each thread uses only its own local variables.
2
Read-only access: all threads only read the data, never write.
3
Proper synchronization: locks, atomic variables, or other mechanisms enforce ordering.

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.

Thread A count Thread B READ: 5 5 READ: 5 5 WRITE: 6 6 WRITE: 6 6 Expected 7, got 6!

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.

// Thread A if (map.containsKey("x")) { // CHECK int val = map.get("x"); // ACT } // Thread B (runs between CHECK and ACT) map.remove("x"); // Invalidates the check!

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

1
Identify shared state: find every variable or object that more than one thread can access.
2
Check for writes: if all accesses are reads, there is no race. At least one thread must modify the data.
3
Look for compound actions: operations like read-modify-write or check-then-act that involve multiple steps on shared data.
4
Verify synchronization: is there a synchronized block, Lock, or Atomic variable protecting the compound action?
5
Imagine interleaving: mentally interleave the steps of two threads. Can any ordering produce a wrong result?

Example 1: Unsafe Counter

class Counter { private int count = 0; public void increment() { count++; // NOT atomic: read → add → write } public int getCount() { return count; } }

Fixing the Counter: Three Approaches

synchronized
Wrap the method or block in a lock: only one thread executes at a time.
AtomicInteger
Use AtomicInteger.incrementAndGet(): hardware-level atomic operation, no lock needed.
ReentrantLock
Explicit lock with try/finally: more flexible than synchronized, allows timed waits.
// Fix with synchronized public synchronized void increment() { count++; } // Fix with AtomicInteger private AtomicInteger count = new AtomicInteger(0); public void increment() { count.incrementAndGet(); }

Example 2: Lazy Initialization

class Singleton { private static Singleton instance; public static Singleton getInstance() { if (instance == null) { // CHECK instance = new Singleton(); // ACT } return instance; } }
Thread A Thread B instance == null? ✓ instance == null? ✓ new Singleton() #1 new Singleton() #2 Two instances created!

Example 3: Compound Map Operation

// Even with ConcurrentHashMap, this is UNSAFE ConcurrentHashMap<String, Integer> map = new ...; // Thread A and Thread B both run: Integer val = map.get("score"); // READ map.put("score", val + 1); // WRITE

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.

class StopFlag { private boolean running = true; // NOT volatile! public void stop() { running = false; } public void run() { while (running) { // May NEVER see the update! // spin forever... } } }

Common Mistakes

✕ "It works on my machine"
Testing passes on a single core but fails on multi-core. Race conditions depend on hardware timing.
✕ Synchronizing only writes
Both reads AND writes to shared data must be synchronized. An unsynchronized read can see stale data.
✕ Using thread-safe collections carelessly
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?

Question 2 of 5

Which three conditions must all be true for a race condition to exist?

Question 3 of 5

What type of race condition is present in this code?

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?

Question 5 of 5

Which of the following scenarios is free from race conditions?