Sub topic 14
Explicit Locks with ReentrantLock
Earlier chapters protected shared data with the synchronized keyword. Java also has a second way to lock: a lock you create as an object and control by calling methods on it. This chapter shows how to use that kind of lock safely, and when you would pick it over synchronized.
What an Explicit Lock Is
A lock is a tool that lets only one thread at a time run a piece of code. With synchronized, the lock is hidden inside every Java object. Java takes the lock and releases it for you.
An explicit lock is a lock you create yourself as a normal object. You call lock() to take it and unlock() to give it back. Nothing happens on its own. You decide where the lock starts and where it ends.
The most common explicit lock in Java is ReentrantLock. It lives in the package java.util.concurrent.locks. A package is a named group of related Java classes.
The word reentrant means a thread that already holds the lock can take it again without blocking itself. You saw this idea with intrinsic locks. ReentrantLock works the same way, and that is where its name comes from.
Why It Matters
synchronized is simple and safe. So why use anything else? An explicit lock can do things synchronized cannot:
- It can try to get the lock and give up if the lock is busy.
- It can wait for the lock for a set time only.
- It can stop waiting if the thread is interrupted. An interrupt is a signal one thread sends to another to ask it to stop what it is doing.
- It can be made fair, so threads get the lock in the order they asked for it.
These extras come with a cost. You must release the lock yourself. If you forget, no other thread can ever get it.
The Basic Pattern: lock, try, finally
Here is a counter protected by a ReentrantLock:
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();
}
}
}Every method follows the same steps:
- Call
lock.lock()to take the lock. If another thread holds it, this thread waits. - Open a
tryblock and do the work on shared data. - Call
lock.unlock()insidefinally.
A finally block is code that always runs when the try block ends. It runs whether the code finishes normally, returns early, or throws an exception. So the lock is always released.
Notice that get() also takes the lock. Reading needs the lock too. Releasing a ReentrantLock gives the same visibility guarantee as leaving a synchronized block. The next thread that takes the lock sees every write made before the unlock.
Let's test the counter with two threads:
public class LockedCounterDemo {
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());
}
}Save both classes in the same folder and run LockedCounterDemo. It prints 200000 every time.
Reentrancy in Action
A thread can lock a ReentrantLock more than once. The lock keeps a hold count, which is the number of times the current thread has locked it. Each unlock() lowers the count by one. Other threads can get the lock only when the count reaches zero.
import java.util.concurrent.locks.ReentrantLock;
public class ReentrancyDemo {
private static final ReentrantLock lock = new ReentrantLock();
static void outer() {
lock.lock();
try {
System.out.println("outer, hold count = " + lock.getHoldCount());
inner();
} finally {
lock.unlock();
}
}
static void inner() {
lock.lock();
try {
System.out.println("inner, hold count = " + lock.getHoldCount());
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
outer();
System.out.println("after, hold count = " + lock.getHoldCount());
}
}The output is:
outer, hold count = 1
inner, hold count = 2
after, hold count = 0If the lock were not reentrant, inner() would wait forever for a lock its own thread already holds.
Trying Without Waiting Forever: tryLock
tryLock() asks for the lock and returns right away. It returns true if the thread got the lock and false if it did not. A second version waits up to a time limit you give it.
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
public class TryLockDemo {
private static final ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Thread holder = new Thread(() -> {
lock.lock();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
lock.unlock();
}
});
holder.start();
Thread.sleep(100); // give holder time to take the lock
if (lock.tryLock(500, TimeUnit.MILLISECONDS)) {
try {
System.out.println("Got the lock");
} finally {
lock.unlock();
}
} else {
System.out.println("Lock is busy, doing something else");
}
holder.join();
}
}The holder thread keeps the lock for two seconds. The main thread waits only half a second, then gives up and prints Lock is busy, doing something else.
Only call unlock() when tryLock returned true. That is why the try/finally sits inside the if.
tryLock also helps with deadlock. A thread that cannot get its second lock can release its first lock and try again later, instead of waiting forever.
Other Useful Features
lockInterruptibly() works like lock(), but the thread stops waiting if it is interrupted. It throws InterruptedException when that happens. Use it when a waiting thread must be able to cancel.
A fair lock hands the lock to the thread that has waited longest. You create one with new ReentrantLock(true). Fair locks are slower, so the default is unfair. Use fairness only when you see some threads waiting much too long.
ReentrantLock vs synchronized
| Feature | synchronized | ReentrantLock |
|---|---|---|
| Releases the lock automatically | Yes | No, you call `unlock()` in `finally` |
| Reentrant | Yes | Yes |
| Try without waiting (`tryLock`) | No | Yes |
| Wait with a time limit | No | Yes |
| Stop waiting on interrupt | No | Yes, with `lockInterruptibly()` |
| Fair ordering option | No | Yes |
| Amount of code | Small | More |
A simple rule: start with synchronized. Switch to ReentrantLock when you need one of its extra features.
Common Mistakes
- Forgetting
unlock(). The lock stays held forever, and every other thread waits forever. - Unlocking outside
finally. An exception skips theunlock()call. - Calling
lock()insidetry. See the warning above. - Unlocking too many times. Calling
unlock()more times thanlock()throwsIllegalMonitorStateException. - Unlocking from a different thread. Only the thread that holds the lock may release it.
- Making a new lock in each call. The lock must be a shared field, usually
private final. A lock created inside a method protects nothing, because each thread gets its own lock.
Exercise
This method compiles but has a bug. What is it, and how do you fix it? public void increment() { lock.lock(); count++; lock.unlock(); }
Show answer
If count++ or any code between lock() and unlock() throws an exception, unlock() never runs and the lock stays held forever. Fix it by putting the work in a try block and unlock() in a finally block: lock.lock(); try { count++; } finally { lock.unlock(); }
Exercise
A thread calls lock.lock() three times in nested methods. How many times must it call unlock() before another thread can take the lock, and what is the hold count after the second unlock()?
Show answer
It must call unlock() three times. After the second unlock() the hold count is 1, so the lock is still held and other threads must keep waiting.
Exercise
You want a thread to skip a cache refresh if another thread is already refreshing, instead of waiting. Which ReentrantLock method fits, and when should the thread call unlock()?
Show answer
Use tryLock(). If it returns true, do the refresh inside try and call unlock() in finally. If it returns false, skip the refresh and do not call unlock(), because the thread never got the lock.