Why this matters
- The
count++race is the canonical concurrency bug, and understanding why it happens explains almost every other one. volatileis routinely used wheresynchronizedis required, which produces code that works in testing and fails under load.- Thread safety is the most common area for follow-up questions in a backend interview, because the wrong answer is so easy to give confidently.
A race condition
count++ compiles to three steps: read the field, add one, write it back. Two threads can read the same
value, both compute the same result, and both write it. One increment disappears.
The two problems, separately
- Atomicity. The read-modify-write sequence can be interleaved. Another thread may act between any two steps.
- Visibility. Each thread may cache the field in a CPU register or a core-local cache. A write by one thread is not guaranteed to become visible to another without a synchronisation point.
synchronized
Acquiring a monitor gives mutual exclusion and a memory barrier in one.
What a monitor guarantees
- Mutual exclusion — only one thread holds a given monitor at a time, so the block is atomic with respect to other synchronised blocks on the same monitor.
- Visibility — releasing a monitor flushes the thread's writes; acquiring it invalidates cached reads. Everything done before the release is visible to the next acquirer.
- Reentrancy — a thread already holding a monitor can acquire it again, which is why one synchronised method may call another.
Both the read and the write must be synchronised. A synchronised increment with an unsynchronised get
fixes atomicity and leaves visibility broken.
Instance versus static locks
These are different monitors, so an instance method and a static method do not exclude each other.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 6 sections
- volatile
- Atomic classes
- The ABA problem
- ThreadLocal
- The hierarchy of solutions
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.