Sub topic 7
Synchronized Blocks and Private Lock Objects
In the last chapter you marked whole methods as synchronized. That works, but it is a blunt tool. The whole method becomes locked, even the parts that never touch shared data. The lock is also the object itself (this), so any other code that holds a reference to your object can use the same lock.
This chapter shows a more precise tool: the synchronized block. You will learn how to lock only the lines that need it, and how to pick a lock that outside code cannot interfere with.
What a Synchronized Block Is
A synchronized block is a group of statements that only one thread at a time can run for a given lock. You write it like this:
public class BlockSyntax {
private final Object lock = new Object();
private int value = 0;
public void update() {
synchronized (lock) {
value = value + 1;
}
}
}The expression in the parentheses is the lock object, which is the object whose lock a thread must hold to enter the block. Any Java object can be a lock. When a thread reaches the block, it tries to take the lock. If another thread already holds that lock, the thread waits. When the thread leaves the block, it releases the lock, even if it leaves because of an exception.
The code inside the block is called a critical section, which is a piece of code that must not run on two threads at once.
A synchronized method is really just a shortcut. These two methods behave the same way:
public class SameThing {
private int count = 0;
public synchronized void incrementA() {
count++;
}
public void incrementB() {
synchronized (this) {
count++;
}
}
}Why Keep the Critical Section Small
While one thread holds a lock, every other thread that needs it must wait. If the block contains slow work, such as building strings, reading files, or calling the network, all the other threads wait for that work too. Your program slows down even though the slow work did not need protection.
The rule is simple: put only the lines that read or change shared data inside the block. Do everything else outside.
Here is an event log that follows this rule:
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();
}
}
}Building entry uses only local variables. A local variable is a variable declared inside a method. Each thread gets its own copy, so local variables are never shared. That line can safely run outside the lock. Only events.add(entry) touches the shared list, so only that line is locked.
Notice that size() also locks. Reading shared data needs the same lock as writing it. Without the lock, a reader could see the list halfway through a change, or might not see recent changes at all.
You can test the class with this program. Save it as EventLogDemo.java next to EventLog.java:
public class EventLogDemo {
public static void main(String[] args) throws InterruptedException {
EventLog log = new EventLog();
Runnable task = () -> {
for (int i = 0; i < 1_000; i++) {
log.add("event " + i);
}
};
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(log.size());
}
}It always prints 2000. If you remove the synchronized (lock) line from add, a plain ArrayList can lose entries or throw an exception. A plain ArrayList is not safe for several threads at once.
Why Use a Private Lock Object
When you write synchronized on a method, the lock is this. Any code that can see your object can also lock on it. That gives strangers control over your lock.
Look at what a careless caller could do:
public class Intruder {
public static void main(String[] args) throws InterruptedException {
SafeCounter counter = new SafeCounter();
Thread hog = new Thread(() -> {
synchronized (counter) {
try {
Thread.sleep(5_000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
hog.start();
Thread.sleep(100);
long start = System.currentTimeMillis();
counter.increment();
System.out.println("Waited ms: " + (System.currentTimeMillis() - start));
}
}
class SafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int get() {
return count;
}
}The hog thread holds the counter's lock for five seconds, so increment() waits about five seconds. The counter did nothing wrong. Outside code just took its lock.
A private lock object fixes this. If the lock is a private field, no outside code can reach it, so only your class decides when it is held. That is why EventLog uses private final Object lock = new Object();.
Choosing and Using a Lock Object
| Lock choice | Who can use the lock | Good idea? |
|---|---|---|
| `synchronized` method (locks `this`) | Your class and any code holding a reference | Fine for simple classes |
| `private final Object lock` | Only your class | Best default |
| A string literal like `"lock"` | Any code anywhere using the same literal | No |
| A boxed number like `Integer` | Possibly unrelated code sharing a cached value | No |
| `new Object()` created inside the method | Nobody else, so it protects nothing | No |
Mistake: A New Lock Each Time
This code compiles and runs, but it does not protect anything:
public class BrokenCounter {
private int count = 0;
public void increment() {
Object lock = new Object();
synchronized (lock) {
count++;
}
}
}Each call creates its own new lock object, so two threads never wait for each other. A lock only works when every thread uses the same object.
Mistake: Different Locks for the Same Data
If add locks on lock but size locks on this, the two methods do not block each other. They use different locks. Choose one lock for each piece of shared data, and use it everywhere that data is read or written.
Mistake: Shrinking the Block Too Far
Keep the block small, but not smaller than the action that must happen as one step. If you check a value and then change it based on that check, both steps belong in the same block:
import java.util.ArrayList;
import java.util.List;
public class UniqueList {
private final Object lock = new Object();
private final List<String> items = new ArrayList<>();
public boolean addIfAbsent(String item) {
synchronized (lock) {
if (items.contains(item)) {
return false;
}
items.add(item);
return true;
}
}
}If contains and add were in two separate blocks, another thread could add the same item between them.
Summary
- A synchronized block locks only the statements inside it, using the lock object you name.
- Keep slow work that does not touch shared data outside the block.
- Use a
private final Objectas the lock so outside code cannot hold it. - Use the same lock for every read and write of the same data.
- Keep a check and the action that depends on it inside one block.
The next chapter looks at how these locks work inside the JVM, including what happens when a thread tries to take a lock it already holds.
Exercise
In the EventLog class, why is the line that builds the entry string placed outside the synchronized block, while events.add(entry) is inside it?
Show answer
The entry string is built from a local variable and the current time. Each thread has its own copy of local variables, so no other thread can see or change them, and no lock is needed. The events list is shared by all threads, so adding to it must be locked. Keeping the string work outside the block means other threads wait less.
Exercise
A class uses "synchronized (this)" in its write method and "synchronized (lock)" in its read method, where lock is a private final Object. Is the shared data protected? Explain.
Show answer
No. The two methods use different lock objects, so a reader and a writer can run at the same time. Every access to the same shared data must use the same lock.
Exercise
Why is "private final Object lock = new Object();" safer than declaring the methods synchronized?
Show answer
Synchronized methods lock on this, and any code with a reference to the object can lock on it too, which can block or slow your methods. A private lock cannot be reached from outside the class, so only your own code decides when it is held. Making it final ensures the field always refers to the same lock object.
Exercise
Rewrite this method so that it is thread-safe using a private lock: "public void addIfAbsent(String s) { if (!items.contains(s)) { items.add(s); } }", where items is a shared ArrayList.
Show answer
Add a field "private final Object lock = new Object();" and put both the check and the add in one block: "public void addIfAbsent(String s) { synchronized (lock) { if (!items.contains(s)) { items.add(s); } } }". The check and the add must be in the same block so no other thread can add the same item between them.