Sub topic 7
Synchronized Blocks and Private Lock Objects
In the last chapter you marked whole methods synchronized. That works, but it locks the entire method body. Often only one or two lines touch shared data. A synchronized block lets you lock just those lines.
What a Synchronized Block Is
A synchronized block is a piece of code wrapped in synchronized (someObject) { ... }. The object in the parentheses is the lock object, the object that threads take turns holding. Only one thread at a time can run code guarded by the same lock object. Other threads wait at the door until it is free.
The part of the code inside the block is called the critical section. A critical section is code that must not run in two threads at once.
A Worked Example
Here is an event log that many threads can write to:
import java.util.ArrayList;
import java.util.List;
public class EventLog {
private final Object lock = new Object();
private final List<String> events = new ArrayList<>();
public void add(String event) {
String entry = System.currentTimeMillis() + " " + event;
synchronized (lock) {
events.add(entry);
}
}
public int size() {
synchronized (lock) {
return events.size();
}
}
}Look at add(). Building the entry string uses only local variables. A local variable is a variable that belongs to one method call, so other threads cannot see it. That step needs no lock. Only events.add(entry) touches the shared list, so only that line sits inside the block.
size() also reads the list, so it uses the same lock. Every access to events must go through the same lock object. If one method forgets the lock, the protection breaks.
Why Keep the Block Small
While one thread holds the lock, every other thread that needs it must wait. A smaller critical section means shorter waits and a faster program. Keep slow work that touches no shared data outside the block, such as building strings, doing math on locals, or reading files.
Why Use a Private Lock Object
You could write synchronized (this), which is what a synchronized method does. But this is public. Any outside code holding your object can also lock it:
synchronized (myLog) {
Thread.sleep(60_000); // blocks every add() and size() call for a minute
}The field lock is private, so no outside code can reach it. Only your class decides when the lock is held. It is also final, so the field can never point to a different object. If two threads locked two different objects, they would not block each other at all.
| Choice | Who can lock it | Risk |
|---|---|---|
| `synchronized` method or `synchronized (this)` | Any code with a reference to the object | Outside code can block your methods |
| `synchronized (lock)` with a private final field | Only your class | Low |
Exercise
In EventLog, why is the line that builds the entry string outside the synchronized block, and what would go wrong if size() read events without synchronizing on lock?
Show answer
Building the string uses only local variables, which no other thread can see, so it needs no lock. Keeping it outside makes the critical section shorter. If size() skipped the lock, it could read the list while another thread is in the middle of changing it, or it could see a stale value. All access to shared data must use the same lock.