Card 02/ 09
All 9 cards
ExampleDifficulty: Intermediate1 min
A Synchronized Method on a Shared Counter
The counter that lost updates, with one keyword added, and the same two threads running the same loops.
class Counter {
private int count = 0;
synchronized void increment() { count++; }
synchronized int count() { return count; }
}2000count++ is still three steps. What has changed is that a second thread cannot be inside increment while the first is, so the three steps cannot be interleaved with another three.
Line 4 matters as much as line 3 and is easier to leave out. A thread reading the count without the lock could see a value from before the last increment was published, which is the other failure wearing its usual disguise.