Lesson · Multithreading Fundamentals
Race Conditions: when two threads lose a write
14 min readRace Conditions
A race condition is an interleaving you did not plan for. The smallest example is one line of code — counter++ — that is secretly three operations, and two threads that run them in the wrong order.
Why races exist
Threads share the heap. When two threads touch the same variable, the CPU is free to interleave their instructions in any order — there is no rule that T1's line finishes before T2's begins.
The result looks impossible at the source level: both threads ran, both incremented, and the final value is 1 instead of 2. Nothing crashed. A write simply vanished.
The lost update, step by step
counter++ is not one operation. It compiles to three: LOAD the value into a register, ADD one, STORE it back. The race lives in the gap between LOAD and STORE.
If both threads LOAD before either STOREs, they both compute from the same starting value — and the second STORE silently overwrites the first. Step through the timeline below to watch it happen, then watch synchronized close the gap.
Two threads · one counter
Shared counter
0
register = —
register = —
Two threads, one shared counter = 0. Each will run counter++ exactly once, so the correct answer is 2. Keep that number in mind.
Making the increment atomic
synchronized puts a monitor around the whole read-modify-write: one thread runs the block, the other waits — the two operations become indivisible. The cost is contention: blocked threads are not doing work.
AtomicInteger.incrementAndGet() gets the same guarantee without a lock, using a CAS loop (compare-and-swap) that retries if another thread got there first. Under heavy contention, LongAdder stripes the counter across cells so threads rarely collide at all — fastest for statistics where reads are rare.
Where races hide
Any check-then-act on shared state is a race: if (!map.containsKey(k)) map.put(k, v) — between the check and the act, another thread can act. So is lazy initialization, and so is updating two fields that must agree (a size and a backing array).
volatile does not fix any of this. It guarantees visibility and ordering — a reader will see the latest write — but counter++ through a volatile field still loses updates, because the read and the write are still two separate steps. Visibility is not atomicity.
What to remember
Prefer in order: immutability (no shared mutation), confinement (the state stays on one thread), and only then synchronization. Locks are the fallback, not the default.
When you must lock, lock consistently — one lock per invariant, acquired in a fixed order — or you have traded a race condition for a deadlock. Stress tests like jcstress exist because races hide from ordinary unit tests.
i++ is three operations
LOAD, ADD, STORE. Ask any candidate why counter++ is unsafe and you will hear 'it is not atomic' — the follow-up is to name the three steps and show where the interleaving loses a write. That is the whole interview.
Interview angles
Why is counter++ thread-safe or not — what actually happens?+
It compiles to LOAD, ADD, STORE. Two threads can both LOAD the same value before either STOREs, so one write is overwritten — a lost update. Fix: synchronized, AtomicInteger, or LongAdder.
Does volatile fix counter++?+
No. volatile guarantees visibility and ordering (readers see the latest write), but it does not make read-modify-write atomic. The race between LOAD and STORE remains. Use it for flags and safe publication, not counters.
When is LongAdder better than AtomicInteger?+
Under heavy contention: AtomicInteger retries CAS on one hot cell, LongAdder spreads writes across cells (striping) so threads rarely collide. LongAdder reads sum the cells, so it wins when writes are frequent and reads are rare.
How does synchronized create ordering guarantees?+
Monitor release/acquire establishes happens-before: everything a thread did before releasing the lock is visible to the next thread that acquires the same lock. That is why the guarded block behaves as one atomic, ordered unit.