Topic 22 of 30 · Advanced
Why is volatile count++ still a race?
volatile provides visibility and ordering guarantees for reads and writes, but count++ is a read-modify-write sequence. Two threads can read the same value and each publish the same increment.
Java 17+; compile each complete program as Main.java.
Detailed answer
volatile provides visibility and ordering guarantees for reads and writes, but count++ is a read-modify-write sequence. Two threads can read the same value and each publish the same increment.
Use synchronized for multi-field invariants or AtomicInteger for a single atomic update. LongAdder favors high-throughput aggregation, but its sum is not a linearizable snapshot under concurrent updates.
A flag can use volatile when its invariant is a single read/write. Check-then-act operations across multiple variables require stronger coordination even when every field is volatile.
Internal working
The Java memory model establishes happens-before relationships; mutual exclusion and atomic compound updates are separate properties.
Practical scenario
A request counter drops increments during a load test even though the field is volatile.
import java.util.concurrent.atomic.AtomicInteger;
class Main {public static void main(String[] a){var c=new AtomicInteger();c.incrementAndGet();System.out.println(c.get());}}Common mistakes
- Equating visibility with atomicity.
- Using LongAdder for unique sequence numbers.
Key takeaways
- Compound operations need atomicity.
- Match primitives to invariants.
- Visibility alone does not prevent races.
Follow-up challenges
- When is synchronized preferable to atomics?
- What does happens-before guarantee?