Sub topic 6
Synchronized Methods
In earlier chapters, two threads broke a shared counter. Part of the problem was that count++ is not one step. The other part was that one thread might not see what another thread wrote. Java gives you a simple tool that fixes both problems at once: the synchronized keyword.
What synchronized means
A lock is a token that only one thread can hold at a time. Every Java object has its own built-in lock.
A synchronized method is a method marked with the synchronized keyword. Before a thread runs the method, it must get the lock of the object the method belongs to. If another thread already holds that lock, the new thread waits. When the method finishes, the lock is released.
This gives you two guarantees:
- Atomicity. Only one thread runs the method body at a time, so the read, add, and write steps of
count++cannot interleave with another thread's. - Visibility. When a thread releases the lock, its writes are made visible to the next thread that gets the same lock.
A safe counter
public class SafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
}Both methods are synchronized, so all access to count goes through the same object's lock. Note that get() is synchronized too. Without that, a reader could skip the lock and see an old value.
Here is a program that runs it. Save it as CounterDemo.java in the same folder as SafeCounter.java.
public class CounterDemo {
public static void main(String[] args) throws InterruptedException {
SafeCounter counter = new SafeCounter();
Runnable task = () -> {
for (int i = 0; i < 100_000; i++) {
counter.increment();
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(counter.get());
}
}This prints 200000 every time.
Which lock is used?
| Method kind | Lock it uses |
|---|---|
| `synchronized` instance method | The object itself (`this`) |
| `static synchronized` method | The class object (`SafeCounter.class`) |
The lock belongs to an object. Two threads using two different SafeCounter objects do not block each other.
The cost
Threads waiting for a lock do no work while they wait. Keep synchronized methods short. The next chapter shows how to lock only the part of a method that needs it.
Exercise
A class has a synchronized increment() method and a plain, unsynchronized get() method that returns count. Is the class thread-safe? Why or why not?
Show answer
No. get() does not take the lock, so nothing guarantees it sees the latest value written by increment(). Visibility is only guaranteed between threads that use the same lock. Make get() synchronized too.
Exercise
Thread A calls increment() on counter1 and Thread B calls increment() on counter2, both SafeCounter objects. Does Thread B have to wait for Thread A?
Show answer
No. Each instance method locks its own object, so counter1 and counter2 have separate locks and the two threads run at the same time.