Card 02/ 09

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.

java
class Counter {
    private int count = 0;
    synchronized void increment() { count++; }
    synchronized int count() { return count; }
}
text
2000
every run, on every machine

count++ 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.