Java Race Conditions
A Java race condition happens when two or more threads use the same data at the same time and the result depends on which thread runs first. The program works most of the time, then suddenly gives a wrong answer, because the thread scheduler decided on a different order.
Race conditions are the most common bug in multithreaded code. This lesson shows how they appear, why simple operations like count++ are not safe, and how to fix them with synchronized, atomic variables and locks.
What Is a Race Condition in Java?
A race condition needs three things: shared data, at least two threads, and at least one thread that changes the data. If any one of these is missing, there is no race.
The classic example is a counter that two threads increase at the same time.
public class LostUpdate {
static int likeCount = 0; // shared and unprotected
public static void main(String[] args) throws InterruptedException {
Runnable clickLike = () -> {
for (int i = 0; i < 100_000; i++) {
likeCount++; // read, add 1, write: three separate steps
}
};
Thread userA = new Thread(clickLike);
Thread userB = new Thread(clickLike);
userA.start();
userB.start();
userA.join();
userB.join();
System.out.println("expected: 200000");
System.out.println("actual : " + likeCount);
}
}
Output (different on every run):
expected: 200000
actual : 137512
How it works:
- Each thread adds 1 to
likeCountone hundred thousand times, so the answer should be 200,000. - The real result is smaller, and it changes every time you run the program.
- Some increments are lost: both threads read the same old value, both add 1, and both write back the same new value. Two clicks are counted as one.
Note: A race condition may not appear on your machine during testing and then appear on a busy server. "It worked when I ran it" proves nothing for multithreaded code.
Why count++ Is Not Atomic
likeCount++ looks like one operation, but the JVM runs it as three steps: read the value, add one, and write the result back. Another thread can run between any of these steps.
| Time | Thread A | Thread B | likeCount in memory |
|---|---|---|---|
| 1 | reads 41 | 41 | |
| 2 | reads 41 | 41 | |
| 3 | adds 1 → 42 | 41 | |
| 4 | adds 1 → 42 | 41 | |
| 5 | writes 42 | 42 | |
| 6 | writes 42 | 42 (one update lost) |
The same thing happens with any read-modify-write sequence. The next example makes the gap between the read and the write longer with Thread.sleep(), so the race happens on every run.
public class ReadModifyWrite {
static int balance = 1000; // shared bank balance
static void withdraw(String customer, int amount) {
int current = balance; // 1. read
System.out.println(customer + " read balance " + current);
pause(100); // the other thread runs here
balance = current - amount; // 2. modify + 3. write
System.out.println(customer + " wrote balance " + balance);
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread alice = new Thread(() -> withdraw("alice", 300));
Thread bob = new Thread(() -> withdraw("bob", 500));
alice.start();
bob.start();
alice.join();
bob.join();
System.out.println("final balance: " + balance + " (expected 200)");
}
}
Output (the order of the lines can change):
alice read balance 1000
bob read balance 1000
alice wrote balance 700
bob wrote balance 500
final balance: 500 (expected 200)
How it works:
- Both threads read
1000before either of them writes. - Alice writes
1000 - 300 = 700, then Bob overwrites it with1000 - 500 = 500. - Rs. 800 was withdrawn but the balance only dropped by Rs. 500. Alice's withdrawal was lost.
Check-Then-Act Race Condition in Java
The second common type of race is check-then-act: a thread checks a condition and then acts on it, but another thread changes the data between the check and the action.
public class TicketRace {
static int seatsLeft = 1; // only one seat in the show
static void book(String customer) {
if (seatsLeft > 0) { // check
pause(50); // e.g. payment processing
seatsLeft--; // act
System.out.println(customer + " booked a seat");
} else {
System.out.println(customer + ": sold out");
}
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] customers = {
new Thread(() -> book("Asha")),
new Thread(() -> book("Ravi")),
new Thread(() -> book("Meena"))
};
for (Thread c : customers) c.start();
for (Thread c : customers) c.join();
System.out.println("seats left: " + seatsLeft);
}
}
Output (order can change):
Asha booked a seat
Ravi booked a seat
Meena booked a seat
seats left: -2
How it works:
- All three threads run the check
seatsLeft > 0while the value is still1, so all three pass. - Each one then decreases
seatsLeft, and the theatre sells three tickets for one seat. - The check was correct when it ran, but it was stale by the time the thread acted on it.
Other check-then-act examples are "create the file if it does not exist", "put into the map if the key is missing" and lazy initialisation (if (instance == null) instance = new ...).
How to Fix a Race Condition with synchronized
The fix is to make the check and the action (or the read and the write) happen as one indivisible step. The simplest tool is synchronized, covered in detail in Java Synchronization.
public class TicketFixed {
static int seatsLeft = 1;
// Only one thread at a time can run this method
static synchronized void book(String customer) {
if (seatsLeft > 0) {
pause(50);
seatsLeft--;
System.out.println(customer + " booked a seat");
} else {
System.out.println(customer + ": sold out");
}
}
static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
Thread[] customers = {
new Thread(() -> book("Asha")),
new Thread(() -> book("Ravi")),
new Thread(() -> book("Meena"))
};
for (Thread c : customers) c.start();
for (Thread c : customers) c.join();
System.out.println("seats left: " + seatsLeft);
}
}
Output (which customer wins can change):
Ravi booked a seat
Asha: sold out
Meena: sold out
seats left: 0
How it works:
static synchronizedlocks on theTicketFixed.classobject, so only one thread can be insidebook()at a time.- The thread that gets the lock checks and decreases
seatsLeftbefore anyone else can look at it. - The other two threads wait for the lock, then see
seatsLeft == 0and report "sold out".
Note: Every access to the shared variable must use the same lock. If one method is
synchronizedbut another method changesseatsLeftwithout the lock, the race comes back.
Fixing Race Conditions with AtomicInteger
For a single number, AtomicInteger is faster than a lock. Its methods do the read, change and write in one hardware-level step.
| Method | What it does atomically |
|---|---|
incrementAndGet() | ++value, returns the new value |
getAndIncrement() | value++, returns the old value |
addAndGet(delta) | value += delta |
compareAndSet(expected, newValue) | sets newValue only if the current value is still expected |
updateAndGet(function) | applies a function and stores the result |
The example below fixes the lost-update counter and the ticket booking with compareAndSet().
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicFix {
static final AtomicInteger likeCount = new AtomicInteger();
static final AtomicInteger seatsLeft = new AtomicInteger(2);
static final AtomicInteger booked = new AtomicInteger();
static final AtomicInteger soldOut = new AtomicInteger();
// Book one seat without a lock, using compare-and-set
static boolean tryBook() {
while (true) {
int current = seatsLeft.get();
if (current == 0) {
return false; // nothing left
}
if (seatsLeft.compareAndSet(current, current - 1)) {
return true; // we took a seat
}
// another thread changed seatsLeft in between: read again and retry
}
}
public static void main(String[] args) throws InterruptedException {
Runnable clickLike = () -> {
for (int i = 0; i < 100_000; i++) {
likeCount.incrementAndGet();
}
};
Thread userA = new Thread(clickLike);
Thread userB = new Thread(clickLike);
userA.start(); userB.start();
userA.join(); userB.join();
System.out.println("likes: " + likeCount.get());
Thread[] customers = new Thread[5];
for (int i = 0; i < customers.length; i++) {
customers[i] = new Thread(() -> {
if (tryBook()) booked.incrementAndGet(); else soldOut.incrementAndGet();
});
customers[i].start();
}
for (Thread c : customers) c.join();
System.out.println("booked: " + booked.get() + ", sold out: " + soldOut.get()
+ ", seats left: " + seatsLeft.get());
}
}
Output:
likes: 200000
booked: 2, sold out: 3, seats left: 0
How it works:
incrementAndGet()never loses an update, so the counter always reaches 200,000.compareAndSet(current, current - 1)only succeeds if no other thread changedseatsLeftsince this thread read it. If it fails, the loop reads the new value and tries again.- Five customers compete for two seats, and exactly two succeed on every run.
Fixing a Race Condition with ReentrantLock
ReentrantLock from java.util.concurrent.locks does the same job as synchronized, with extra features such as timeouts. Always unlock in a finally block, so the lock is released even if an exception is thrown.
import java.util.concurrent.locks.ReentrantLock;
public class WalletWithLock {
private final ReentrantLock lock = new ReentrantLock();
private int balance = 1000;
boolean withdraw(int amount) {
lock.lock(); // wait until we own the lock
try {
if (balance < amount) {
return false; // check and act inside the lock
}
balance -= amount;
return true;
} finally {
lock.unlock(); // always release the lock
}
}
int balance() {
lock.lock();
try {
return balance;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
WalletWithLock wallet = new WalletWithLock();
Thread[] shoppers = new Thread[4];
int[] successes = new int[4];
for (int i = 0; i < shoppers.length; i++) {
int index = i;
shoppers[i] = new Thread(() -> {
for (int j = 0; j < 100; j++) {
if (wallet.withdraw(5)) successes[index]++;
}
});
shoppers[i].start();
}
for (Thread s : shoppers) s.join();
int total = successes[0] + successes[1] + successes[2] + successes[3];
System.out.println("successful withdrawals: " + total);
System.out.println("final balance: " + wallet.balance());
}
}
Output:
successful withdrawals: 200
final balance: 0
How it works:
- Four threads try 400 withdrawals of Rs. 5 from a wallet holding Rs. 1000.
- The balance check and the subtraction both happen while the thread holds
lock, so only 200 withdrawals succeed and the balance stops at exactly 0. balance()also locks, so a reader never sees a half-finished update. Each thread writes only its own slot ofsuccesses, andmainreads them afterjoin().
Race Conditions vs Data Races
The two terms are related but not the same. You can have a race condition even when every single operation is thread-safe.
| Data race | Race condition | |
|---|---|---|
| Meaning | Two threads access the same variable, at least one writes, and there is no synchronization | The result depends on the timing of threads |
| Example | Plain int updated by two threads | if (!map.containsKey(k)) map.put(k, v) on a ConcurrentHashMap |
| Fixed by thread-safe classes alone? | Usually yes | No, the combined steps must be atomic |
The ConcurrentHashMap example has no data race, because each call is safe. It still has a race condition, because two threads can both pass the containsKey check. Single atomic methods such as putIfAbsent() and computeIfAbsent() solve this, as shown in Java Thread Safety.
Real-World Example: A Coupon Redemption Service
A festival sale coupon can be used at most 50 times in total and once per user. Ten checkout threads process 200 redemption attempts at the same time, because each user taps the button twice. Every rule must hold no matter how the threads interleave.
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
public class CouponService {
enum Result { REDEEMED, ALREADY_USED, LIMIT_REACHED }
private final int maxRedemptions;
private final Set<String> usedBy = new HashSet<>(); // guarded by "this"
private int redeemedCount = 0; // guarded by "this"
CouponService(int maxRedemptions) {
this.maxRedemptions = maxRedemptions;
}
// Both checks and both updates run as one atomic step
synchronized Result redeem(String userId) {
if (usedBy.contains(userId)) {
return Result.ALREADY_USED;
}
if (redeemedCount >= maxRedemptions) {
return Result.LIMIT_REACHED;
}
usedBy.add(userId);
redeemedCount++;
return Result.REDEEMED;
}
synchronized int redeemedCount() {
return redeemedCount;
}
public static void main(String[] args) throws InterruptedException {
CouponService festivalSale = new CouponService(50);
Map<Result, LongAdder> stats = new ConcurrentHashMap<>();
Thread[] checkoutThreads = new Thread[10];
for (int t = 0; t < checkoutThreads.length; t++) {
int threadNo = t;
checkoutThreads[t] = new Thread(() -> {
for (int i = 0; i < 10; i++) {
String userId = "user-" + (threadNo * 10 + i);
for (int attempt = 0; attempt < 2; attempt++) { // every user taps twice
Result result = festivalSale.redeem(userId);
stats.computeIfAbsent(result, key -> new LongAdder()).increment();
}
}
});
checkoutThreads[t].start();
}
for (Thread checkout : checkoutThreads) checkout.join();
System.out.println("total attempts : 200");
new TreeMap<>(stats).forEach((result, count) ->
System.out.printf("%-14s : %d%n", result, count.sum()));
System.out.println("redeemed count : " + festivalSale.redeemedCount());
}
}
Output:
total attempts : 200
REDEEMED : 50
ALREADY_USED : 50
LIMIT_REACHED : 100
redeemed count : 50
How it works:
- Two check-then-act rules. "Has this user already redeemed?" and "Is the limit reached?" are both checks followed by updates. Putting all of them inside one
synchronizedmethod removes both races. - Guarded state.
usedByis a plainHashSetandredeemedCountis a plainint. They are safe only because every access goes through a method that locksthis. - The proof. 100 users tap twice. The first 50 users to get the lock redeem the coupon, and their second tap returns
ALREADY_USED(50). The other 50 users getLIMIT_REACHEDon both taps (100). Which 50 users win changes between runs, but the totals never do. - Statistics.
ConcurrentHashMap.computeIfAbsent()with aLongAddercounts results from ten threads without losing any.
When the threads in this example need to hold two locks at the same time, a new danger appears: threads waiting for each other forever. That problem is covered in the next lesson, Java Deadlocks. To review how main waits for the worker threads, see Java Thread Join.