Sub topic 8
How Intrinsic Locks Work: Monitors and Reentrancy
In the last two chapters you used synchronized methods and synchronized blocks. This chapter looks at the machinery underneath them. You will learn what a lock really is, which lock each kind of synchronized code uses, and why a thread is allowed to take a lock it already holds.
Every Object Has a Built-In Lock
A lock is a tool that lets only one thread at a time run a piece of code. In Java, every object comes with one lock built in. This is called the object's intrinsic lock. It is also called a monitor. Both names mean the same thing.
You never create an intrinsic lock yourself. When you write new Object() or new ArrayList<>(), the new object already has its lock. The synchronized keyword is how you use it.
A lock has three basic actions:
- Acquire. A thread takes the lock. A thread does this when it enters
synchronizedcode. - Hold. While a thread holds the lock, no other thread can acquire it.
- Release. The thread gives the lock back when it leaves the
synchronizedcode.
A thread releases the lock when it leaves the code in either of two ways. It might finish normally, or it might leave because an exception was thrown. Either way, Java releases the lock for you. That is one reason synchronized is hard to misuse.
Which Lock Does Each Form Use?
The synchronized keyword always locks some object. The form you write decides which object that is.
| Code you write | Lock that is used |
|---|---|
| `synchronized void m()` (instance method) | The object the method is called on (`this`) |
| `static synchronized void m()` | The class object, for example `Counter.class` |
| `synchronized (lock) { ... }` | The object named in the parentheses (`lock`) |
The rule that matters here: the lock belongs to an object, not to a method. Two different synchronized methods on the same object share one lock. So while one thread is inside increment(), another thread cannot enter get() on that same object.
The reverse also holds. If you have two different objects, they have two different locks. Thread A can run increment() on counter1 while thread B runs increment() on counter2 at the same moment. Neither blocks the other.
What Happens When a Lock Is Busy
If a thread tries to acquire a lock that another thread holds, it stops and waits. Java calls this thread state BLOCKED. The waiting thread does nothing until the lock is released. Then it gets a chance to acquire it.
The program below shows this. One thread holds a lock for two seconds. A second thread tries to take the same lock, and the main thread prints its state.
public class BlockedDemo {
private static final Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread holder = new Thread(() -> {
synchronized (lock) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
Thread waiter = new Thread(() -> {
synchronized (lock) {
System.out.println("Waiter got the lock");
}
});
holder.start();
Thread.sleep(100); // give holder time to take the lock
waiter.start();
Thread.sleep(100); // give waiter time to reach the lock
System.out.println("Waiter state: " + waiter.getState());
holder.join();
waiter.join();
}
}When you run it, you will usually see:
Waiter state: BLOCKED
Waiter got the lockThe second line appears about two seconds later, after holder leaves its synchronized block. The short sleeps make this order very likely, but thread timing is never fully guaranteed.
Reentrancy: Taking a Lock You Already Hold
Suppose a thread holds an object's lock and then calls another synchronized method on the same object. It asks for a lock it already has. What happens?
In Java, it simply goes in. Intrinsic locks are reentrant. A reentrant lock is one that the thread already holding it can acquire again without waiting.
public class ReentrancyDemo {
public synchronized void outer() {
System.out.println("In outer, holds lock: " + Thread.holdsLock(this));
inner();
System.out.println("Back in outer");
}
public synchronized void inner() {
System.out.println("In inner, holds lock: " + Thread.holdsLock(this));
}
public static void main(String[] args) {
new ReentrancyDemo().outer();
}
}Output:
In outer, holds lock: true
In inner, holds lock: true
Back in outerThread.holdsLock(obj) is a built-in method. It returns true if the current thread holds the lock of obj. It is handy for checking your understanding.
How Java Keeps Track: The Hold Count
Java keeps two facts for each lock:
- the owner, meaning which thread holds it, if any
- a hold count, meaning how many times the owner has acquired it
Each time the owner enters synchronized code on that object, the count goes up by one. Each time it leaves, the count goes down by one. The lock is free again only when the count is back to zero. In the demo above, the count goes 0 → 1 (enter outer) → 2 (enter inner) → 1 (leave inner) → 0 (leave outer).
Why Reentrancy Matters
Picture Java without reentrancy. In the demo, outer() holds the lock and calls inner(). inner() would wait for the lock to be free. But the lock belongs to the same thread, which is now stuck waiting. It would wait forever. A thread waiting on itself like this is called a self-deadlock.
Reentrancy also makes inheritance safe. A common case looks like this:
class Account {
protected int balance = 0;
public synchronized void deposit(int amount) {
balance += amount;
}
}
class LoggingAccount extends Account {
@Override
public synchronized void deposit(int amount) {
System.out.println("Depositing " + amount);
super.deposit(amount); // needs the same lock again
}
}
public class InheritanceDemo {
public static void main(String[] args) {
LoggingAccount account = new LoggingAccount();
account.deposit(50);
System.out.println("Balance: " + account.balance);
}
}Both methods lock the same object, account. The subclass method holds the lock and then calls super.deposit, which asks for it again. Because of reentrancy, this works and prints Balance: 50.
Common Mistakes With Intrinsic Locks
Once you know a lock belongs to an object, several bugs become easy to spot.
- Changing the lock field. If you write
lock = new Object();while threads are running, different threads may lock different objects. Declare lock fieldsfinal. - Locking on shared constants. String literals like
"lock"and small boxed numbers likeInteger.valueOf(1)can be the same object across your whole program, even in libraries you did not write. Unrelated code could then compete for your lock. Usenew Object()instead. - Locking a new object every time.
synchronized (new Object()) { ... }protects nothing, because each thread gets its own fresh lock. - Mixing locks for one field. If one method guards
countwiththisand another guards it with a private lock, the two methods can run at the same time. Pick one lock for each piece of shared state.
Summary
- Every Java object has one intrinsic lock, also called a monitor.
synchronizedmethods lockthis,static synchronizedmethods lock the class object, and blocks lock the object you name.- A thread waiting for a busy lock is in the BLOCKED state.
- Intrinsic locks are reentrant. The owner thread can acquire a lock again, and a hold count tracks how many times. The lock becomes free when the count reaches zero.
- Without reentrancy, a
synchronizedmethod calling another one on the same object would deadlock.
Exercise
A class has public synchronized void a() and public static synchronized void b(). Thread 1 calls obj.a() and Thread 2 calls MyClass.b() at the same time. Does either thread block the other? Why?
Show answer
No. a() locks the instance obj, while b() locks the class object MyClass.class. These are two different objects with two different locks, so both threads can run at once.
Exercise
A thread calls synchronized method outer(), which calls synchronized middle(), which calls synchronized inner(), all on the same object. What is the hold count while inner() runs, and when can another thread acquire the lock?
Show answer
The hold count is 3 while inner() runs. It drops to 2, then 1, then 0 as each method returns. Another thread can acquire the lock only after outer() returns and the count reaches 0.
Exercise
Why is synchronized ("lock") { ... } a bad idea, and what should you write instead?
Show answer
String literals with the same text are shared across the whole program, so unrelated code locking on "lock" would compete for the same lock. Use a dedicated field instead: private final Object lock = new Object(); and write synchronized (lock) { ... }.