Why is count++ not thread-safe?
Strong answer
count++ contains a read, an addition, and a write. Two threads can read the same old value and overwrite each other's updates, so the compound action is not atomic.
Reason about visibility, atomicity, ordering, races, synchronized, volatile, locks, and safe publication.
Advanced Java · concurrency
Use the strong answer as your reference, explain it aloud in your own words, then choose how soon you want to review it again.
Interview prompt
Strong answer
Concurrency correctness requires atomicity, visibility, and ordering. The Java Memory Model defines happens-before relationships that let one thread safely observe another thread's writes. synchronized provides mutual exclusion and visibility; volatile provides visibility and ordering for a variable but does not make compound operations atomic.
Key points
Interviewer looks for
Use a concrete race condition and explain exactly which guarantee is missing: atomicity, visibility, or ordering.
Java example
1final class Counter {
2 private final AtomicInteger value = new AtomicInteger();
3 int increment() { return value.incrementAndGet(); }
4}Topic interview questions
These questions are tied to this lesson. Read each question aloud, then compare your explanation with the strong answer.
Strong answer
count++ contains a read, an addition, and a write. Two threads can read the same old value and overwrite each other's updates, so the compound action is not atomic.
Strong answer
A volatile write is visible to later reads of that variable and establishes ordering around the access. volatile does not make multi-step operations such as increment or check-then-act atomic.
Strong answer
synchronized provides mutual exclusion for the protected monitor and establishes visibility when a thread releases and another thread acquires the same monitor. It also gives a clear happens-before relationship.
Strong answer
It is a Java Memory Model ordering guarantee: if action A happens-before action B, B must see A's effects and A cannot be reordered after B in a way observable through the model. Locks, volatile, thread start, and thread join create such edges.
Strong answer
Use a happens-before mechanism such as final fields with proper construction, a volatile reference, a lock, a concurrent collection, or static initialization. Avoid exposing this before the constructor finishes.
How well do you know this?
Your review choice is saved locally and synced to your learner profile when signed in.