Sub topic 14
Explicit Locks with ReentrantLock
You already know how synchronized protects shared data. Java also gives you a lock you can hold and control in your own code. It is called ReentrantLock, and it lives in the package java.util.concurrent.locks.
What Is an Explicit Lock?
An explicit lock is a lock you create as a normal object and then lock and unlock with method calls. With synchronized, Java locks and unlocks for you. With an explicit lock, you do both steps yourself.
Reentrant means the thread that holds the lock can lock it again without blocking itself. Java keeps a count of how many times the thread has locked it. The lock is free again only after the thread calls unlock() the same number of times.
Why Use It?
ReentrantLock can do a few things that synchronized cannot:
tryLock()tries to get the lock and returnsfalseright away if another thread holds it. Your thread does not get stuck waiting.tryLock(time, unit)waits only for a set amount of time.lockInterruptibly()lets another thread interrupt a thread that is waiting for the lock.
If you don't need any of these, plain synchronized is simpler and safer.
The Golden Rule: Unlock in finally
Java never releases an explicit lock for you. Suppose the code between lock() and unlock() throws an exception and you skip unlock(). The lock then stays held forever, and every other thread that wants it waits forever.
To prevent this, call lock() just before a try block, and call unlock() inside finally. A finally block always runs, even when the try block throws an exception.
Worked Example
This counter uses a ReentrantLock to guard count. The main method starts two threads that each add 100,000.
import java.util.concurrent.locks.ReentrantLock;
public class LockedCounter {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int get() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
LockedCounter counter = new LockedCounter();
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 program always prints 200000. Only one thread at a time can run count++, so no update is lost. get() also takes the lock. That makes sure it reads the latest value.
synchronized vs. ReentrantLock
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Releases the lock automatically | Yes | No, you must call `unlock()` |
| Reentrant | Yes | Yes |
| Try without waiting | No | Yes, with `tryLock()` |
| Waiting can be interrupted | No | Yes, with `lockInterruptibly()` |
Exercise
A method calls lock.lock(), then updates a list, then calls lock.unlock(), with no try/finally. What goes wrong if the list update throws an exception?
Show answer
The exception skips the unlock() call, so the lock stays held forever. Any other thread that calls lock() then waits forever. The fix is to put the update in a try block and call unlock() in finally.
Exercise
A thread holding a ReentrantLock calls lock() on it a second time. Does it block, and how many unlock() calls are needed to free the lock?
Show answer
It does not block, because the lock is reentrant. The hold count goes up to 2, so the thread must call unlock() twice before other threads can get the lock.