Correctness: races on shared state 00:00:00 Make a prediction You will calculate the result of a lost update and use an invariant to check a proposed synchronization boundary. Five notebooks are in stock. Two sales both read five, subtract one and write four. What quantity does the system report after serving both customers? Four, though the correct stock is three. Each subtraction was locally reasonable. The combined interleaving lost one update, so protect the complete read-modify-write operation. 00:00:32 Two windows, one shed Two ticket windows look through the same telescope at the last seat. Both announce it free. Putting a padlock on each separate window still leaves two different locks protecting the same seat. All participants enforcing one invariant must share the right coordination mechanism. Correctness must hold for every permitted interleaving, including reads that promise a consistent view. Correctness under concurrency means that the rules of your objects hold for every possible mix of steps by different threads. The rules are ordinary ones, such as: a telescope is free or on one loan. What is new is that another thread may act between any two of your steps. Races do not show up like other bugs. The code looks right, the tests are green, and the failure appears under load, on other hardware, once in a while. By then the damage is data: a seat sold twice, points that vanished, a total that does not add up. 00:01:32 Catch a lost increment Five notebooks are available. Two sales each read five, subtract one and write four. Two customers were served, yet the recorded quantity fell by only one. Separate safe reads and writes do not protect the whole read-modify-write sequence. Use an atomic update or protect the entire operation. With the update serialized, one sale takes five to four and the next takes four to three. The expected final quantity is three. Both workers read five. Both compute six. Storing six twice loses one increment even though neither write recorded a strange numeric value. A legal sequential run would finish at seven. That comparison gives a test oracle for the entire operation, not just individual memory accesses. 00:02:23 Preserve an invariant across fields A transfer moves ten dollars from one account to another. If only the withdrawal is protected, an observer can see a debit without its matching credit. Put the transfer inside the required consistency boundary and design reads that promise a consistent total to use that boundary too. The total starts at eighty. After a full transfer it should still be eighty, with forty in each account. A reader observing after the debit and before the credit can see only seventy. Individually safe counters alone do not preserve a multi-field observation. Protecting just the writes can still let readers see a partially completed transfer. Define what a reader is promised and synchronize it accordingly. For a single counter, an atomic update may suffice; for a cross-object invariant, the boundary must cover both sides. Java ConcurrentHashMap. Its documentation says the entire computeIfAbsent call is performed atomically. This is the compound step that containsKey and put do not give you. Java LongAdder. Documented as giving significantly higher throughput than AtomicLong under high contention, at the expense of more space. One value, spread over cells. 00:03:39 Try an interview follow-up How is a data race different? A data race is about memory: conflicting accesses without an order between them. A race condition is about meaning. Two calls to a thread-safe set with a gap between them have no data race, and still a race condition. Start with stock one. Two simultaneous reservations both return success. Could either order of those operations produce both replies while preserving the stock rule? No. Use this small history as a correctness test. Now change the history so one caller gets sold out, and identify a valid order for those replies. 00:04:24 What to take with you A race needs shared data, a change, and steps that can be mixed. Remove one of them. Try confinement and immutability first, since they cost no waiting. Use a lock when a rule needs several fields or a check before a change: one private lock for all fields of the rule, held from the first look to the last write, by readers as well. Atomics are for one value. Split locks only where no rule crosses. Keep the outside world out of the lock with reserve, call, confirm. Prove it by argument, by forced orders, and last by stress.