Java Race Conditions and How to Spot and Fix Them Fast
Reproduce lost updates and check then act races in Java, learn the patterns that signal a race, fix them with atomics and locks and test for them under load.

A race condition is the bug that passes every test on your laptop and corrupts data in production on the day traffic doubles. The code is not clearly wrong; it assumes two threads will not interleave in one particular unlucky way, and at scale they do. This post builds three classic races in small programs, shows the wrong output they produce, fixes each in the lightest way that works and shows how to test for them. The foundation is the Java memory model, explained in happens-before and the Java Memory Model; this post is its practical companion.
Race one: the lost update
The simplest race is an increment. count++ looks like one operation and is three: read the field, add one, write it back.
package dev.javahacks.race;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
public class LostUpdate {
private int count = 0;
void increment() {
count++;
}
public static void main(String[] args) throws Exception {
var counter = new LostUpdate();
try (var pool = Executors.newFixedThreadPool(8)) {
IntStream.range(0, 8).forEach(i -> pool.submit(() -> {
for (int n = 0; n < 100_000; n++) counter.increment();
}));
}
System.out.println("expected 800000, got " + counter.count);
}
}expected 800000, got 512847The number varies run to run, which is itself the signature of a race. When two threads read the same value before either writes, both write value plus one and one increment is lost. The leaving try block of the executor waits for the tasks (ExecutorService implements AutoCloseable since Java 19), so the print sees the final value.
The fix depends on how much you are protecting. For a single counter, use an atomic class, whose incrementAndGet is one hardware level compare and swap:
private final AtomicInteger count = new AtomicInteger();
void increment() {
count.incrementAndGet();
}For a counter updated by many threads at high rate, LongAdder spreads the contention across cells and sums on read, which is faster under heavy write load; see AtomicLong and LongAdder. When a lock is the better fit because several fields change together, synchronized works the same way:
synchronized void increment() { count++; }Race two: check then act
The second shape is subtler because the individual operations are thread safe. A cache that checks for a key and then inserts it:
package dev.javahacks.race;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
public class CheckThenAct {
static final Map<String, ExpensiveConfig> CACHE = new ConcurrentHashMap<>();
static final AtomicInteger LOADS = new AtomicInteger();
static ExpensiveConfig get(String tenant) {
ExpensiveConfig cfg = CACHE.get(tenant); // check
if (cfg == null) {
cfg = load(tenant); // expensive, 100 ms
CACHE.put(tenant, cfg); // act
}
return cfg;
}
static ExpensiveConfig load(String tenant) {
LOADS.incrementAndGet();
try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
return new ExpensiveConfig(tenant);
}
record ExpensiveConfig(String tenant) {}
}Every call to ConcurrentHashMap is atomic, and the code is still wrong. Between get returning null and put executing, another thread can do the same check. Ten threads asking for the same tenant at startup each see null and each load it, so LOADS ends at ten instead of one. With a config object that is merely expensive, this wastes time. With one that has side effects, such as opening a connection or registering a listener, it is a real bug. The map is thread safe; the sequence is not.
The fix is to use the one method that does check and act atomically:
static ExpensiveConfig get(String tenant) {
return CACHE.computeIfAbsent(tenant, CheckThenAct::load);
}computeIfAbsent runs the loader at most once per key and makes other threads for the same key wait for the result. There is one rule to follow: the loader must be short and must not touch the same map, because it runs while the map holds an internal lock on that bin. A slow loader belongs in a Caffeine loading cache, as in Caffeine versus Guava versus Ehcache. The related ConcurrentHashMap methods are in compute and merge for atomic updates.
Race three: visibility and unsafe publication
The third family is not about interleaved operations but about one thread never seeing another's write. A stop flag is the standard example:
class Worker implements Runnable {
private boolean running = true; // not volatile
public void run() {
while (running) { doWork(); } // may never see the update
}
public void stop() { running = false; }
}Without volatile, the JIT is allowed to hoist the read of running out of the loop, and the worker spins forever after stop() is called. The fix is private volatile boolean running, which creates a happens-before edge between the write in one thread and the read in another. The same reasoning applies to publishing an object: if one thread constructs an object and hands it to another through a plain field, the second thread may see a partially constructed instance. Safe publication means a final field, a volatile reference, a lock or a concurrent collection. Volatile versus synchronized versus atomic lays out when each one is enough.
How to spot a race in code review
Four patterns reliably indicate a risk. A non-final field that is written by more than one method and not protected by a lock. A compound operation, x = x + 1, if (!map.containsKey(k)) map.put(k, v), list.size() followed by list.get(i), on shared state. A lazily initialised field, if (instance == null) instance = new .... And any mutable object shared by reference between a request thread and a background thread. When you see one, ask what happens if a second thread runs the same lines at the same moment.
Testing for races
A passing single threaded test says nothing. To raise the odds of exposing a race, force many threads to start at the same instant and repeat:
class LostUpdateTest {
@RepeatedTest(20)
void counterDoesNotLoseUpdates() throws Exception {
var counter = new SafeCounter();
int threads = 16, perThread = 50_000;
var start = new CountDownLatch(1);
try (var pool = Executors.newFixedThreadPool(threads)) {
for (int i = 0; i < threads; i++) {
pool.submit(() -> {
start.await(); // release all threads together
for (int n = 0; n < perThread; n++) counter.increment();
return null;
});
}
start.countDown();
}
assertThat(counter.get()).isEqualTo(threads * perThread);
}
}The latch makes every worker begin at once, which maximizes contention. Even so, a green run is weak evidence; it only fails if the schedule happened to interleave badly. For serious concurrency code use OpenJDK's jcstress, a harness built to explore interleavings and memory model outcomes, and review the code for the patterns above. More on this approach is in testing concurrent code to find race conditions.
Choosing the fix
| Situation | Fix |
|---|---|
| One counter | AtomicInteger, AtomicLong or LongAdder |
| Check then insert into a map | computeIfAbsent, compute, merge |
| Several fields change together | synchronized or ReentrantLock around the group |
| A flag or reference read by other threads | volatile |
| Data not shared | Remove the sharing: use confinement or immutable objects |
The last row is the best fix when it is available. A race needs shared mutable state; remove one of the two words and it cannot occur.
A review checklist for races
When reviewing concurrent code, walk each shared variable and ask who writes it, who reads it and what orders them. If the answer includes the phrase "it should be fine because", look for the happens-before edge that makes it true: a lock, a volatile, a final field or a concurrent collection. If you cannot name it, there is not one. Look at every compound operation on shared state and ask whether two threads running it at once could produce a result no sequential order could. Finally check the tests: a test that cannot fail is not evidence, so prefer one that starts many threads together and repeats.
When this does not apply
If your component is single threaded, such as an event loop that serializes all access, none of this applies, though a handoff between loops still needs safe publication. If your data lives in a database, the equivalent races are lost updates between transactions, handled with locking or isolation, covered in handling concurrent updates in JPA. The reference for the guarantees is the Java Language Specification chapter 17 on threads and locks, and the jcstress project is the harness for testing them.


