Race conditions
suggest changeA race condition is a bug where the result of a program depends on the timing of threads: which one runs first, or whether one thread is paused in the middle of an operation while another runs. The program works most of the time, so tests pass, and then it fails now and then in production.
Two related terms are worth separating:
- A data race is a narrow, technical term from the Java Memory Model: two threads access the same variable, at least one of them writes, and nothing orders the accesses (no
synchronized,volatile, lock or other happens-before edge). Data races can give stale or surprising values. - A race condition is the broader problem: a sequence of operations that must happen as a unit but doesn't. You can have a race condition with no data race at all, for example when every call goes to a thread-safe
ConcurrentHashMapbut two calls together are not atomic.
Almost every race condition is one of three patterns:
| Pattern | Example | Typical fix |
|---|---|---|
| read-modify-write | count++ |
AtomicInteger, LongAdder, synchronized |
| check-then-act | if (balance >= x) balance -= x |
do the check and the act under one lock, or use one atomic method |
| broken invariant across variables | lower and upper updated separately |
guard all of them with one lock, or keep them in one immutable object |
This article shows each pattern with a program you can run, then the fixes.
Lost updates: read-modify-write
count++ looks like one operation but it is three: read count, add 1, write count back. If two threads both read 41, both write 42, and one increment is lost.
public class LostUpdate {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
for (int run = 1; run <= 5; run++) {
count = 0;
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
for (int j = 0; j < 100_000; j++) {
count++;
}
});
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("run " + run + ": count = " + count + " (expected 400000)");
}
}
}
One run printed:
run 1: count = 112791 (expected 400000)
run 2: count = 257376 (expected 400000)
run 3: count = 400000 (expected 400000)
run 4: count = 400000 (expected 400000)
run 5: count = 400000 (expected 400000)
The first run lost more than 70% of the increments. The later runs came out right, most likely because by then the JIT compiler had optimized the loop so it writes count far less often, which shrinks the window in which threads can collide. The code is no more correct in run 5 than in run 1. This is what makes race conditions dangerous: the same broken code can pass a test and fail the next time.
Fixing it
There are three common fixes. All of them make the read-modify-write a single indivisible step:
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;
public class Fixes {
static int plain = 0;
static int locked = 0;
static final Object lock = new Object();
static final AtomicInteger atomic = new AtomicInteger();
static final LongAdder adder = new LongAdder();
public static void main(String[] args) throws InterruptedException {
Runnable work = () -> {
for (int j = 0; j < 100_000; j++) {
plain++;
synchronized (lock) {
locked++;
}
atomic.incrementAndGet();
adder.increment();
}
};
Thread[] threads = new Thread[4];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(work);
threads[i].start();
}
for (Thread t : threads) {
t.join();
}
System.out.println("plain int: " + plain);
System.out.println("synchronized: " + locked);
System.out.println("AtomicInteger: " + atomic.get());
System.out.println("LongAdder: " + adder.sum());
}
}
plain int: 393973
synchronized: 400000
AtomicInteger: 400000
LongAdder: 400000
synchronizedworks for any block of code, not just a counter. See Synchronization.AtomicInteger.incrementAndGet()uses a hardware compare-and-swap instruction, with no locking. See Atomic Types.LongAdderspreads updates over several internal cells and adds them up insum(). It is the best choice for a counter that many threads update and few read, such as request statistics.
volatile is not enough
A common mistake is to mark the counter volatile. volatile guarantees that every thread sees the latest written value, but it does not make count++ atomic:
public class VolatileCount {
static volatile int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(VolatileCount::work);
Thread b = new Thread(VolatileCount::work);
a.start(); b.start();
a.join(); b.join();
System.out.println("count = " + count + " (expected 200000)");
}
static void work() {
for (int i = 0; i < 100_000; i++) {
count++; // still read, add, write: not atomic
}
}
}
count = 184765 (expected 200000)
Use volatile for a value that one thread writes and others read (a flag, a reference to an immutable config object). For read-modify-write use an atomic class or a lock.
Check-then-act
The second pattern is checking a condition and then acting on it, when another thread can change the condition in between. The classic example is a bank withdrawal:
import java.util.concurrent.CountDownLatch;
public class Overdraft {
static class Account {
private long balance;
Account(long balance) { this.balance = balance; }
boolean withdraw(long amount) throws InterruptedException {
if (balance >= amount) { // check
Thread.sleep(1); // e.g. log or call a fraud-check service
balance -= amount; // act
return true;
}
return false;
}
long balance() { return balance; }
}
public static void main(String[] args) throws InterruptedException {
int overdrawn = 0;
for (int run = 0; run < 100; run++) {
Account acc = new Account(100);
CountDownLatch start = new CountDownLatch(1);
Runnable customer = () -> {
try {
start.await();
acc.withdraw(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Thread a = new Thread(customer);
Thread b = new Thread(customer);
a.start();
b.start();
start.countDown(); // release both threads at once
a.join();
b.join();
if (acc.balance() < 0) overdrawn++;
}
System.out.println("runs with a negative balance: " + overdrawn + " / 100");
}
}
runs with a negative balance: 53 / 100
Both threads see a balance of 100, both pass the check, and both withdraw. The Thread.sleep(1) stands in for real work between the check and the update. Without it the window is a few nanoseconds wide and the bug shows up rarely, but it is still there.
The CountDownLatch is a useful trick for testing: all threads wait on start.await() and are released at the same moment, which makes collisions much more likely than if each thread started whenever start() got to it.
The fix is to make the check and the act one atomic step. Here the simplest way is synchronized on both methods:
static class Account {
private long balance;
Account(long balance) { this.balance = balance; }
synchronized boolean withdraw(long amount) throws InterruptedException {
if (balance >= amount) {
Thread.sleep(1);
balance -= amount;
return true;
}
return false;
}
synchronized long balance() { return balance; }
}
runs with a negative balance: 0 / 100
Note that balance() is also synchronized. A reader without the lock could see a stale value. Every access to shared mutable state needs the same lock, not just the writes.
Holding a lock while sleeping or calling a remote service is fine for correctness, but every other thread waiting for the account is blocked meanwhile. In real code, keep the slow part outside the lock when you can.
Thread-safe collections don't make your code thread-safe
A ConcurrentHashMap guarantees that each individual method call is safe. It can't know that your get and the following put belong together. A word counter written with get and put loses updates exactly like count++:
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MapRace {
public static void main(String[] args) throws Exception {
Map<String, Integer> broken = new ConcurrentHashMap<>();
Map<String, Integer> fixed = new ConcurrentHashMap<>();
String[] words = {"apple", "banana", "cherry"};
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++) {
pool.submit(() -> {
for (int i = 0; i < 30_000; i++) {
String w = words[i % words.length];
// check-then-act: two separate atomic calls, not one
Integer old = broken.get(w);
broken.put(w, old == null ? 1 : old + 1);
// one atomic read-modify-write
fixed.merge(w, 1, Integer::sum);
}
});
}
} // close() waits for all tasks
System.out.println("get + put: " + new TreeMap<>(broken));
System.out.println("merge: " + new TreeMap<>(fixed));
}
}
get + put: {apple=52990, banana=57165, cherry=50873}
merge: {apple=80000, banana=80000, cherry=80000}
ConcurrentHashMap has atomic versions of the common compound operations. Use them instead of combining get, containsKey and put:
| Instead of | Use |
|---|---|
if (!m.containsKey(k)) m.put(k, v) |
m.putIfAbsent(k, v) |
get + put(k, old + 1) |
m.merge(k, 1, Integer::sum) |
if (m.get(k) == null) m.put(k, load(k)) |
m.computeIfAbsent(k, this::load) |
get + compute + put |
m.compute(k, (key, old) -> ...) |
if (m.get(k).equals(old)) m.put(k, v) |
m.replace(k, old, v) |
The lazy cache case deserves a closer look, because the racy version doesn't produce a wrong value. It just does the expensive work many times:
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class CacheRace {
static final AtomicInteger loads = new AtomicInteger();
static String loadConfig(String key) {
loads.incrementAndGet();
try { Thread.sleep(50); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
return "value-of-" + key;
}
static final Map<String, String> cache = new ConcurrentHashMap<>();
static String getRacy(String key) {
String v = cache.get(key);
if (v == null) { // several threads can see null here
v = loadConfig(key);
cache.put(key, v);
}
return v;
}
static String getAtomic(String key) {
return cache.computeIfAbsent(key, CacheRace::loadConfig);
}
static void hammer(String label, Function<String, String> get) throws Exception {
cache.clear();
loads.set(0);
CountDownLatch start = new CountDownLatch(1);
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100; i++) {
pool.submit(() -> {
start.await();
return get.apply("db.url");
});
}
start.countDown();
}
System.out.println(label + " loadConfig calls: " + loads.get());
}
public static void main(String[] args) throws Exception {
hammer("get/put: ", CacheRace::getRacy);
hammer("computeIfAbsent: ", CacheRace::getAtomic);
}
}
get/put: loadConfig calls: 100
computeIfAbsent: loadConfig calls: 1
With 100 requests arriving together, the racy version hits the database 100 times. This is the "cache stampede" that can take down a backend just after a cache is cleared. computeIfAbsent runs the loader once per key while other callers for that key wait. Keep the function passed to it short and don't modify the same map from inside it.
The same problem applies to Collections.synchronizedList, Vector and other synchronized wrappers. Each method takes the lock, but a sequence of calls does not:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SyncListRace {
public static void main(String[] args) {
for (int run = 1; run <= 5; run++) {
List<Integer> racy = Collections.synchronizedList(new ArrayList<>());
List<Integer> safe = Collections.synchronizedList(new ArrayList<>());
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++) {
pool.submit(() -> {
for (int i = 0; i < 1_000; i++) {
// each call is synchronized, the pair is not
if (!racy.contains(i)) {
racy.add(i);
}
// hold the list's own lock for the whole compound action
synchronized (safe) {
if (!safe.contains(i)) {
safe.add(i);
}
}
}
});
}
}
System.out.println("run " + run + ": racy size " + racy.size()
+ ", safe size " + safe.size());
}
}
}
run 1: racy size 1006, safe size 1000
run 2: racy size 1000, safe size 1000
run 3: racy size 1000, safe size 1000
run 4: racy size 1000, safe size 1000
run 5: racy size 1002, safe size 1000
Three runs out of five look correct. The synchronized wrappers use the wrapper object itself as their lock, so synchronized (safe) excludes all other calls on safe. The same rule applies to iteration, which must also be done inside synchronized (list). See Thread-safe Collections and Concurrent Collections.
Invariants that span several variables
Making each field atomic doesn't help when a rule connects the fields. This range must always have lower <= upper, and each setter checks the rule:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class RangeRace {
// invariant: lower <= upper
static class BrokenRange {
final AtomicInteger lower = new AtomicInteger(0);
final AtomicInteger upper = new AtomicInteger(10);
void setLower(int v) {
if (v > upper.get()) throw new IllegalArgumentException();
lower.set(v);
}
void setUpper(int v) {
if (v < lower.get()) throw new IllegalArgumentException();
upper.set(v);
}
}
record Range(int lower, int upper) {
Range {
if (lower > upper) throw new IllegalArgumentException(lower + " > " + upper);
}
}
static class SafeRange {
final AtomicReference<Range> range = new AtomicReference<>(new Range(0, 10));
void setLower(int v) {
range.updateAndGet(r -> new Range(v, r.upper())); // throws if v > upper
}
void setUpper(int v) {
range.updateAndGet(r -> new Range(r.lower(), v));
}
}
public static void main(String[] args) {
int broken = 0;
for (int run = 0; run < 10_000; run++) {
BrokenRange r = new BrokenRange();
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
pool.submit(() -> { try { r.setLower(5); } catch (IllegalArgumentException ignored) {} });
pool.submit(() -> { try { r.setUpper(4); } catch (IllegalArgumentException ignored) {} });
}
if (r.lower.get() > r.upper.get()) broken++;
}
System.out.println("BrokenRange ended with lower > upper: " + broken + " / 10000");
broken = 0;
for (int run = 0; run < 10_000; run++) {
SafeRange r = new SafeRange();
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
pool.submit(() -> { try { r.setLower(5); } catch (IllegalArgumentException ignored) {} });
pool.submit(() -> { try { r.setUpper(4); } catch (IllegalArgumentException ignored) {} });
}
Range snap = r.range.get();
if (snap.lower() > snap.upper()) broken++;
}
System.out.println("SafeRange ended with lower > upper: " + broken + " / 10000");
}
}
BrokenRange ended with lower > upper: 4 / 10000
SafeRange ended with lower > upper: 0 / 10000
In BrokenRange, setLower(5) checks 5 > 10 (passes), setUpper(4) checks 4 < 0 (passes), and both write. The result is lower = 5, upper = 4, a state neither setter allows. It happened 4 times in 10,000, which is the kind of bug that shows up once a week in production and never in a test.
There are two good fixes:
- Guard all the related fields with one lock (
synchronizedmethods on the class). - Put the fields in one immutable object and swap the whole object atomically. That's what
SafeRangedoes: theRangerecord validates itself, andAtomicReference.updateAndGetreplaces the old range with a new one only if no other thread changed it meanwhile, retrying otherwise. Readers always get a consistent snapshot with a singleget().
updateAndGet may call your function more than once when threads collide, so the function must have no side effects.
Compare-and-set loops
updateAndGet, accumulateAndGet and friends are built on compareAndSet(expected, newValue): "set the value to newValue only if it is still expected". When you need custom logic, you can write the loop yourself. Here both styles track the maximum latency seen by many threads:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
public class MaxTracker {
static final AtomicLong maxLatency = new AtomicLong();
// what accumulateAndGet does for you
static void recordWithCas(long latency) {
while (true) {
long current = maxLatency.get();
if (latency <= current) return; // nothing to do
if (maxLatency.compareAndSet(current, latency)) return; // we won
// another thread changed it between get() and compareAndSet(): retry
}
}
static void record(long latency) {
maxLatency.accumulateAndGet(latency, Math::max);
}
public static void main(String[] args) {
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int t = 0; t < 8; t++) {
pool.submit(() -> {
var rnd = ThreadLocalRandom.current();
for (int i = 0; i < 100_000; i++) {
long v = rnd.nextLong(1_000_000);
if (i % 2 == 0) recordWithCas(v); else record(v);
}
});
}
pool.submit(() -> record(1_000_000)); // the true maximum
}
System.out.println("max latency: " + maxLatency.get());
}
}
max latency: 1000000
The naive version, if (latency > max.get()) max.set(latency), is a check-then-act race: a smaller value can overwrite a larger one written between the check and the set.
Visibility: the other half of the problem
Even without compound actions, a thread may never see another thread's write unless the two are connected by a happens-before edge. This worker loops on a plain boolean:
public class StaleFlag {
static boolean stop = false; // try: static volatile boolean stop
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
long spins = 0;
while (!stop) {
spins++;
}
System.out.println("worker saw stop after " + spins + " spins");
});
worker.setDaemon(true); // so the JVM can exit if it never stops
worker.start();
Thread.sleep(500);
stop = true;
worker.join(2000);
System.out.println("worker still running 2 s after stop = true: " + worker.isAlive());
}
}
worker still running 2 s after stop = true: true
The JIT is allowed to read stop once and turn the loop into while (true). With static volatile boolean stop the same program prints:
worker saw stop after 1013222332 spins
worker still running 2 s after stop = true: false
synchronized, volatile, atomic classes, Thread.start/join, ExecutorService.submit/Future.get and concurrent collections all create happens-before edges. If shared mutable state is only ever touched through them, you get visibility for free. More on this in Pitfall - Shared variables require proper synchronization. For stopping threads, prefer interruption, described in Cancellation and timeouts.
Races outside memory: files and databases
Race conditions aren't limited to Java fields. Any shared resource, such as the file system, a database or a remote API, has the same check-then-act problem, and here other processes can be on the other side of the race too.
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class FileRace {
static boolean claimRacy(Path p, String owner) throws IOException {
if (Files.exists(p)) {
return false;
}
Files.writeString(p, owner); // another thread may have created it meanwhile
return true;
}
static boolean claimAtomic(Path p, String owner) throws IOException {
try {
Files.createFile(p); // check and create in one file-system operation
} catch (FileAlreadyExistsException e) {
return false;
}
Files.writeString(p, owner);
return true;
}
interface Claim { boolean claim(Path p, String owner) throws IOException; }
static void race(String label, Claim claim) throws Exception {
Path p = Files.createTempDirectory("race").resolve("job.lock");
AtomicInteger winners = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
try (ExecutorService pool = Executors.newFixedThreadPool(8)) {
for (int i = 0; i < 8; i++) {
String owner = "worker-" + i;
pool.submit(() -> {
start.await();
if (claim.claim(p, owner)) winners.incrementAndGet();
return null;
});
}
start.countDown();
}
System.out.println(label + " workers that think they own the lock: " + winners.get());
Files.delete(p);
Files.delete(p.getParent());
}
public static void main(String[] args) throws Exception {
race("exists + write:", FileRace::claimRacy);
race("createFile: ", FileRace::claimAtomic);
}
}
exists + write: workers that think they own the lock: 8
createFile: workers that think they own the lock: 1
All 8 workers saw that the file didn't exist and all 8 "won". Files.createFile (or Files.newOutputStream with StandardOpenOption.CREATE_NEW) asks the operating system to create the file only if it doesn't exist, as one operation, so exactly one caller succeeds. See also Pitfall - Testing a file before attempting to open it.
The same rule holds for databases. Instead of SELECT followed by INSERT or UPDATE, let the database do it atomically: a unique constraint plus INSERT ... ON CONFLICT, UPDATE accounts SET balance = balance - ? WHERE id = ? AND balance >= ? (then check the update count), or SELECT ... FOR UPDATE inside a transaction.
Virtual threads race too
Virtual threads are scheduled on a pool of platform carrier threads that run in parallel, so everything above applies to them unchanged:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
public class VirtualRace {
static long plain = 0;
static final AtomicLong atomic = new AtomicLong();
public static void main(String[] args) {
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int t = 0; t < 10_000; t++) {
pool.submit(() -> {
for (int i = 0; i < 1_000; i++) {
plain++;
atomic.incrementAndGet();
}
});
}
}
System.out.println("plain: " + plain);
System.out.println("atomic: " + atomic.get());
}
}
plain: 4873775
atomic: 10000000
Half of the plain increments were lost. Since Java 24, synchronized no longer pins a virtual thread to its carrier, so synchronized blocks are a fine fix in virtual-thread code as well.
Finding race conditions
Races are timing dependent, so a single test run proves little. Some practical techniques:
- Stress tests. Run the operation from many threads, many times, and check an invariant at the end, as every example in this article does. Use a
CountDownLatchstart gate so threads collide, and repeat the test in a loop rather than once. - Make the window wider. A temporary
Thread.sleep(1)between the check and the act, like in theOverdraftexample, turns a one-in-a-million bug into a reproducible one. - Review shared state. For every mutable field reachable from more than one thread, ask: which lock guards it, and is every read and write done under that lock? Write it down with a comment like
// guarded by this. A field without an answer is a bug. - jcstress. The OpenJDK Java Concurrency Stress harness runs small concurrent snippets millions of times with different interleavings and reports every observed outcome. It is what the JDK developers use to test the memory model itself.
- Static analysis. Tools like SpotBugs flag inconsistent synchronization, such as a field written under a lock but read without one.
How to avoid race conditions
The best fix is to not have shared mutable state in the first place:
- Immutability. Records,
List.of,Map.copyOfandfinalfields can be shared freely. To change state, build a new object and publish it through anAtomicReferenceor avolatilefield. - Confinement. State used by only one thread can't race. Use local variables,
ThreadLocal(see Using ThreadLocal), or hand objects between threads through aBlockingQueueso that only one thread owns each object at a time. - Let a library do it.
ConcurrentHashMap.merge,LongAdder,AtomicReference.updateAndGet, executors andCompletableFuturehandle the hard parts for you. - One lock per invariant. When state really must be shared and mutable, guard everything that takes part in one invariant with the same lock, and hold it for the whole compound action: the check and the act. See Locks as Synchronisation aids for
ReentrantLockandReadWriteLock. - Database and file system atomics. Use constraints, conditional updates and
CREATE_NEWinstead of checking first.
Summary
- A race condition happens when correctness depends on thread timing. It shows up as lost updates, invariants that don't hold, or work done twice.
count++,if (x) doY()andgetfollowed byputare compound actions that need to be made atomic.volatilegives visibility, not atomicity.- Thread-safe collections make single calls safe. Use their atomic methods (
merge,computeIfAbsent,putIfAbsent) or an external lock for sequences of calls. - Keep related fields under one lock, or in one immutable object swapped with
AtomicReference. - Files and databases have the same races. Use atomic operations like
Files.createFileand conditional SQL updates. - Test with many threads, a start gate and many repetitions. A test that passes once proves nothing about a race.