software-engineer-blog logoSoftware Engineer Blog

Module 7 · Concurrency

Unit 25 of 49

Unit 25 · Module 7 · Concurrency

Race conditions and locks

The bug that only appears under load, and never in your tests.

Unit 25 of the free 49-unit computer-science course, in concurrency. 3 interview questions answered in full and a short self-check.

Nothing published yet

This unit is part of the course map but has no episode or article of its own yet. The units around it do — see what is already published.

Interview questions this unit unlocks

Asked out loud, answered out loud. Read the answer, then say it in your own words.

What is a race condition? Give one you have actually seen.

Two threads read the same value, both decide based on it, and both write — so one update silently disappears. The classic shape is check-then-act: read a balance, confirm it is sufficient, subtract. Between the check and the act another thread does the same, and the account goes negative. Nothing in the code looks wrong, because the bug is in the gap between two correct statements.

The tell that it is a race and not a logic bug: it reproduces under load and vanishes under a debugger.

How do you fix it without a mutex?

Push the atomicity down to something that already has it. A single `UPDATE … SET balance = balance - 10 WHERE balance >= 10` does the check and the act in one statement the database serialises for you. Compare-and-swap does the same in memory: read the value with a version, write only if the version is unchanged, retry if not. Both replace a lock with a value the loser can detect.

What is the difference between optimistic and pessimistic locking?

Pessimistic takes the lock before touching the data and assumes conflict is likely — correct, and it serialises everyone including the readers who would never have collided. Optimistic lets everyone proceed and detects the conflict at write time by comparing a version, then makes the loser retry. Optimistic wins when conflicts are rare; under real contention it turns into a retry storm and pessimistic is cheaper.

Self-check — 3 questions

Answer alone, at 2am, with no interviewer in the room.

Part of Everything You Need to Know About Computer Science.