Check-then-act
foundational · asked in almost every interview
`if (!map.has(k)) map.set(k, v)`, raced against itself. Both threads check, both find it missing, and both create it.
Enumerating the interleavings…
What this shows
The window is between the check and the act. A lock that begins after the check protects nothing; the fix is to ask and act in one indivisible operation.
Why it is asked
The TOCTOU pattern behind a huge share of real bugs — duplicate charges, duplicate accounts, two connections where one was intended.
In an interview
The TOCTOU pattern behind a huge share of real bugs — duplicate charges, duplicate accounts, two connections where one was intended.
- TOCTOU
- atomicity
- putIfAbsent
- idempotency
Run these next
- The lost update`count++` is three operations, not one. Only two of its twenty interleavings produce 2; the failure is the common case, and an atomic increment removes the orderings rather than making them rarer.
- MutexesA lock removes orderings from the space. The critical section must span the whole read-modify-write — guarding only the write leaves the window exactly where it was.