Sub topic 6
Synchronized Methods
In the last few chapters you saw two problems. Two threads can interrupt each other in the middle of count++, which is an atomicity problem. One thread can also miss a value that another thread wrote, which is a visibility problem. This chapter shows the simplest tool Java gives you to fix both at once: the synchronized keyword on a method.
What a synchronized method is
A synchronized method is a method marked with the word synchronized. Only one thread at a time can run a synchronized method on the same object.
It works with a lock. A lock is like a single key to a room. Every Java object has one built-in lock. When a thread calls a synchronized method, it must first take the object's lock. If another thread already holds the lock, the new thread waits. When the method ends, the thread gives the lock back, and a waiting thread can take it.
The code inside the method is now a critical section, a piece of code that only one thread can run at a time.
The fix for the broken counter
Here is a counter that is safe to share between threads:
public class SafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
}Both methods use the same lock: the lock of the SafeCounter object they are called on. Inside a synchronized instance method, the lock is the object that this refers to.
This one keyword fixes both problems:
- Atomicity. The read, add, and write steps of
count++all happen while the thread holds the lock. No other thread can slip in between them. - Visibility. When a thread releases a lock, Java makes sure its writes can be seen by the next thread that takes the same lock. So
get()always sees the latest value.
A worked example you can run
Save SafeCounter.java from above. Then save this file next to it as SafeCounterDemo.java:
public class SafeCounterDemo {
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());
}
}Compile and run it:
javac SafeCounter.java SafeCounterDemo.java
java SafeCounterDemoIt prints 200000 every time. Run it ten times and you get the same answer ten times. The earlier RaceDemo printed a smaller number on most runs because it had no lock.
What happens step by step
The diagram shows two threads competing for the same lock.
A thread that is waiting for a lock is called blocked. It does no work and just waits its turn.
Why get() must be synchronized too
Beginners often lock only the method that writes. That is a mistake.
public class HalfSafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int get() { // not synchronized: a bug
return count;
}
}The writes are atomic, but get() never takes the lock. Java gives no promise that a thread reading without the lock sees the newest value. It might see an old one.
Static synchronized methods
A method can be both static and synchronized. A static method has no this object, so it locks something else: the class object, written IdGenerator.class in the example below. There is exactly one class object per class.
public class IdGenerator {
private static int next = 0;
public static synchronized int nextId() {
return next++;
}
}Every thread that calls IdGenerator.nextId() uses the same lock, so no two threads ever get the same ID.
Which lock is used
| Method kind | Lock it takes | Who shares the lock |
|---|---|---|
| `synchronized` instance method | The object (`this`) | Callers using the same object |
| `static synchronized` method | The class object (`MyClass.class`) | Every caller in the program |
| Plain method | No lock | Nobody, so there is no protection |
Edge cases and common mistakes
Different objects have different locks
If two threads each use their own SafeCounter, they do not block each other. That is fine, because they share no data. It becomes a bug when two objects share data through a static field. A synchronized instance method locks this, and a static field belongs to the whole class, so two objects can still change it at the same time.
Static and instance locks are separate
A static synchronized method and a normal synchronized method in the same class use different locks. If both touch the same field, they do not protect each other.
The lock is released on exceptions
If a synchronized method throws an exception, Java still releases the lock. You never have to unlock it by hand. This makes synchronized hard to misuse.
Overriding drops synchronized
The synchronized word is not inherited. If a subclass overrides increment() without writing synchronized, the new version has no lock. Add the keyword again in the subclass.
Constructors cannot be synchronized
Writing synchronized on a constructor is a compile error. Other threads normally cannot reach an object before its constructor finishes, so a constructor usually does not need a lock.
Do not hold the lock too long
While one thread is inside a synchronized method, every other caller waits. If the method does slow work, such as reading a file or sleeping, the whole program slows down. Keep synchronized methods short. The next chapter shows how to lock only part of a method.
What synchronized does not do
- It does not run threads in a fixed order. Which waiting thread gets the lock next is not decided by you.
- It does not protect fields that some code reads or writes outside the lock.
- It does not make a sequence of separate calls atomic. Calling
counter.get()and thencounter.increment()is two locked steps. Another thread can run between them.
Exercise
A class has a field private int total and two methods: public synchronized void add(int n) { total += n; } and public int getTotal() { return total; }. Two threads call add() on the same object while a third calls getTotal(). What is wrong, and how do you fix it?
Show answer
add() is atomic, but getTotal() reads total without taking the lock, so Java does not promise it sees the latest value. Add the synchronized keyword to getTotal() so that the reads and writes use the same object lock.
Exercise
A class has private static int hits and an instance method public synchronized void hit() { hits++; }. The program creates two objects of this class and gives one to each of two threads. Is hits safe? Why or why not?
Show answer
It is not safe. The instance method locks each object separately, so the two threads hold two different locks and can update the shared static field at the same time. Make the method public static synchronized void hit() so that every caller uses the single class lock.
Exercise
Why does SafeCounterDemo always print 200000, while RaceDemo usually prints less?
Show answer
In SafeCounterDemo, each increment() call takes the counter's lock, so the read, add, and write steps of count++ cannot overlap with another thread's steps. In addition, get() takes the same lock after the threads finish, so it sees every write. RaceDemo has no lock, so increments overlap and some are lost.