← InterviewBeginner
Why Is counter++ Not Safe?
Two threads each run `counter++` a million times on a shared integer. The final value is less than two million. Explain exactly why, and what your options are.
The scenario
A metrics counter in a request handler reports about 4% fewer requests than the load balancer does. It is exact in every test, and the gap grows with traffic.
What it tests
- Whether the candidate can decompose an operation that looks atomic into its actual steps
- Whether they can name a specific failing interleaving rather than saying "it is a race"
- Whether they know more than one remedy and can say what each costs
Answer it out loud first. Recognising a good answer is not the same skill as producing one.