Card 02/ 09
synchronized Example: A Counter That No Longer Loses Updates
One keyword on each method, and the same two threads now always reach 2000.
Adding synchronized to the counter's methods fixes its lost updates: only one thread can be inside increment at a time, so two increments can no longer interleave. Two threads each increment a shared counter a thousand times, and without a lock the total comes out below two thousand, because updates are lost. The same counter with synchronized:
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 one thread's three steps can no longer be mixed with another's.
Line 4 matters as much as line 3, and it is the one people leave out. A thread reading the count without the lock could see a stale value, one written before the last increment was published: a visibility failure, where one thread's write is not yet seen by another.
← → move through sections and cards