Shared state and synchronized
Two threads that add one to the same counter a million times should leave it at a million. They usually do not, and the reason is one sentence: value++ is three steps, a read, an add and a write, and another thread may run between any two of them. This lesson loses updates on purpose and then puts them back with a lock.
A counter without a lock
The counter has a field and one method that increments it. Four threads call that method 250,000 times each, which should give a million:
import java.util.ArrayList;
import java.util.List;
public class Race {
static class Counter {
private long value;
void increment() {
value++;
}
long value() {
return value;
}
}
public static void main(String[] args) throws InterruptedException {
int threads = 4;
int perThread = 250_000;
long expected = (long) threads * perThread;
Counter unsafe = new Counter();
run(unsafe, threads, perThread);
System.out.println("expected: " + expected);
System.out.println("lost updates: " + (unsafe.value() < expected));
Counter safe = new Counter();
runSynced(safe, threads, perThread);
System.out.println("safe: " + safe.value());
System.out.println("complete: " + (safe.value() == expected));
}
static void run(Counter counter, int threads, int perThread) throws InterruptedException {
List<Thread> workers = new ArrayList<>();
for (int i = 0; i < threads; i++) {
Thread worker = new Thread(() -> {
for (int n = 0; n < perThread; n++) {
counter.increment();
}
});
workers.add(worker);
worker.start();
}
for (Thread worker : workers) {
worker.join();
}
}
static void runSynced(Counter counter, int threads, int perThread) throws InterruptedException {
List<Thread> workers = new ArrayList<>();
for (int i = 0; i < threads; i++) {
Thread worker = new Thread(() -> {
for (int n = 0; n < perThread; n++) {
synchronized (counter) {
counter.increment();
}
}
});
workers.add(worker);
worker.start();
}
for (Thread worker : workers) {
worker.join();
}
}
}
javac -Xlint:all Race.java
java Race
expected: 1000000
lost updates: true
safe: 1000000
complete: true
The update that is lost
In the run that wrote this page the unsafe count stopped at 907,466, about ninety thousand increments short, and the figure is different on every run: it depends on where the threads were interrupted. The two threads read the same value, both add one, both write, and one of the two additions disappears. The program prints lost updates: true rather than the size of the loss, because only the boolean is the same on every run.
This is a race condition, and it is not a bug of the counter: the class is correct for one thread and says nothing about several. A program that assumes a method is safe because its code looks short is the one that ships the bug, and the failure appears under load and never in a test.
synchronized
The second run wraps the increment in synchronized (counter), and the count is exactly a million. The block takes the monitor of the object, and only one thread at a time may hold it, so the read, the add and the write happen without another thread in between.
The lock is not a property of the field but of the object that is named. Two counters each have their own monitor, and a block synchronised on one does not stop a thread in a block synchronised on the other. Choosing the object is therefore choosing the scope of the lock, and the smallest scope that is correct is the one to pick.
Synchronised methods
A synchronized method is the same block with the receiver as the monitor. The bank below has a deposit and a balance method that both take the lock of the bank object, so a reader never sees a half-finished deposit:
public class Sync {
static class Bank {
private long balance;
synchronized void deposit(long cents) {
balance += cents;
}
synchronized long balance() {
return balance;
}
}
public static void main(String[] args) throws InterruptedException {
Bank bank = new Bank();
Thread a = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
bank.deposit(100);
}
});
Thread b = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
bank.deposit(100);
}
});
a.start();
b.start();
a.join();
b.join();
System.out.println("balance: " + bank.balance());
System.out.println("expected: 200000");
System.out.println("ok: " + (bank.balance() == 200_000));
}
}
javac -Xlint:all Sync.java
java Sync
balance: 200000
expected: 200000
ok: true
Two thousand deposits of a hundred is 200,000, and the count is exact because the lock serialises the two threads. The same program without synchronized loses deposits, as the first program did, and the loss is small enough that a test of one run may not see it.
What a lock costs
A lock is not free: an uncontended one costs a few nanoseconds, a contended one parks threads and costs microseconds. The first program took a lock a million times, which is why it is slower than the version without one, and the correct answer to a contended lock is usually to hold it less often rather than not at all.
The three shapes of that answer are the next lessons: an atomic variable, which makes the increment one hardware instruction (118); a lock that is taken by a data structure designed for it, such as a ConcurrentHashMap (120); and a task that returns a value instead of sharing one (116). Before any of them, a field that only one thread touches is the best optimisation there is.
Exercises
- Run Race three times and compare the unsafe counts.
- Make the increment lock on a separate object instead of the counter and explain why the count is still right.
- Add a synchronized method that adds a hundred and call it from both threads of Sync.
- Write a version that locks once per thousand increments and say what it does to the race.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is
value++not atomic?Answer
It is a read, an add and a write, and a thread may run between them
Two threads can read the same value and both write value plus one.
-
What does
synchronized (object)take?Answer
The monitor of that object, which only one thread may hold
The object names the lock, and the block runs with it held and released at the end.
-
Why does the program print a boolean for the loss?
Answer
The size of the loss differs on every run, and only the fact is stable
The interleaving depends on the machine, so the exact number is not reproducible.
-
What does this program print?
public class Q1 { static int value; public static void main(String[] args) throws InterruptedException { Thread t = new Thread(() -> { for (int i = 0; i < 1000; i++) { synchronized (Q1.class) { value++; } } }); t.start(); t.join(); System.out.println(value); } }Answer
1000
One thread and a lock still give the exact count, and the join orders the print.
-
What is a race condition?
Answer
A result that depends on the order the threads happen to run in
The bug is in the interleaving, so the same code gives different answers on different runs.
-
What is the monitor of a synchronized instance method?
Answer
The object it is called on
A static synchronized method uses the class, and an instance one uses the instance.
-
Why is locking the smallest object that is enough the right choice?
Answer
The lock stops every thread that needs the same monitor, no more and no less
The monitor decides which threads wait, so a wider lock slows work that did not need to wait.
-
What does this program print?
public class Q2 { static int value; public static void main(String[] args) throws InterruptedException { Thread a = new Thread(() -> value += 2); Thread b = new Thread(() -> value += 3); a.start(); b.start(); a.join(); b.join(); System.out.println(value); } }Answer
5
The joins order the reads, and the additions are both applied to the field.
-
What does a synchronized block guarantee about memory?
Answer
A thread that leaves it has written the changes, and one that enters sees them
The monitor is also a memory barrier, which is what makes the writes visible to the next holder.
-
What is the usual fix for a contended counter?
Answer
Lock less often, or use an atomic variable or a concurrent structure
The next lessons show the atomic classes and the concurrent collections, which do this for a program.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev