What causes a race condition?
Try code in the playgroundUnderstand the concept
A race condition happens when the result depends on the timing of operations that access shared state. JavaScript can have races even on one execution thread because asynchronous work pauses and lets other requests run between a read and a write. Databases and other processes can also update the same data concurrently.
Important ideas
-
Two operations read the same old value, then overwrite each other's changes.
-
Example: two requests both reduce the same stock count.
-
Use an atomic database update, suitable locks or a version check.
-
For stock,
read 5 → subtract 1 → save 4can lose an update if two requests both read 5. -
An atomic conditional update moves the check and change into one database operation.
Can you explain it without the notes?
What causes a race condition?
Use your own words. Explain an example and one limitation before checking the explanation.
Check your explanation
A race condition happens when the result depends on the timing of operations that access shared state. JavaScript can have races even on one execution thread because asynchronous work pauses and lets other requests run between a read and a write. Databases and other processes can also update the same data concurrently.
Turn this concept into a clear answer.
- Explain the exact interleaving that breaks the business rule, then choose a constraint, atomic operation or locking strategy that prevents it.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “What causes a race condition?”. Examples are study fragments; framework behavior can depend on your version.