ReentrantLock and unlock in finally
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A synchronized block takes and releases a lock for you. A ReentrantLock is a lock you hold as a normal object: you call lock() to take it and unlock() to give it back. That gives you more control, and one new duty: you must always release it yourself.
The Lock interface
ReentrantLock is a lock object with lock and unlock methods that offers more control than synchronized, such as timeouts; unlock must always be called in finally.
Lock is an interface in the package java.util.concurrent.locks. It describes a lock that you take and release with method calls. ReentrantLock is the class you will use most often to create one: private final Lock lock = new ReentrantLock();.
Example 1 · A like counter protected by a ReentrantLock
import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;
class LikeCounter { private final Lock lock = new ReentrantLock(); private int likes = 0;
void like() { lock.lock(); try { likes++; } finally { lock.unlock(); } }
int getLikes() { lock.lock(); try { return likes; } finally { lock.unlock(); } }}
public class LockCounterDemo { public static void main(String[] args) throws InterruptedException { LikeCounter counter = new LikeCounter(); Runnable task = () -> { for (int i = 0; i < 100_000; i++) { counter.like(); } };
Thread t1 = new Thread(task, "phone-1"); Thread t2 = new Thread(task, "phone-2"); t1.start(); t2.start(); t1.join(); t2.join();
System.out.println("Likes on the fest poster: " + counter.getLikes()); }}Likes on the fest poster: 200000
What this code does
- Two threads call
like()100,000 times each. The lock lets only one of them runlikes++at a time, so no update is lost and the total is always 200000. getLikes()takes the same lock before reading. That is what makes the latest value visible to the reading thread.- The field type is the interface
Lock, the object is aReentrantLock, just likeListandArrayList.
It protects data in the same way as synchronized. Only one thread at a time can hold the lock, so only one thread at a time runs the code between lock() and unlock(). That code is called the critical section. It also gives the same visibility guarantee. An unlock() happens-before the next lock() of the same lock, so the next thread sees every change made inside the critical section.
private final field. Every thread must use the same lock object, and nobody outside the class should be able to take it.lock() and unlock()
lock() takes the lock. If another thread holds it, the calling thread waits until the lock is free. unlock() releases the lock and lets one waiting thread continue.
Example 2 · Tatkal booking: check and book under one lock
import java.util.concurrent.locks.ReentrantLock;
class TatkalQuota { private final ReentrantLock lock = new ReentrantLock(); private int seatsLeft; private int booked = 0; private int waitlisted = 0;
TatkalQuota(int seats) { this.seatsLeft = seats; }
boolean book() { lock.lock(); try { if (seatsLeft > 0) { // check ... seatsLeft--; // ... and act, under the same lock booked++; return true; } waitlisted++; return false; } finally { lock.unlock(); } }
String report() { lock.lock(); try { return "Booked: " + booked + ", Waitlisted: " + waitlisted + ", Seats left: " + seatsLeft; } finally { lock.unlock(); } }}
public class TatkalLockDemo { public static void main(String[] args) throws InterruptedException { TatkalQuota quota = new TatkalQuota(10); Thread[] counters = new Thread[3]; for (int c = 0; c < 3; c++) { counters[c] = new Thread(() -> { for (int i = 0; i < 5; i++) { quota.book(); } }, "counter-" + (c + 1)); counters[c].start(); } for (Thread t : counters) { t.join(); } System.out.println(quota.report()); }}Booked: 10, Waitlisted: 5, Seats left: 0
What this code does
- Three booking counters try 5 bookings each, so 15 passengers compete for 10 seats. Exactly 10 are booked and 5 are waitlisted on every run.
- The check
seatsLeft > 0and the changeseatsLeft--sit inside one critical section. No other counter can sneak in between them and book the last seat twice. - Both
returnstatements are insidetry, sofinallyreleases the lock on both paths.
Example 3 · Reentrancy: the hold count goes up and down
import java.util.concurrent.locks.ReentrantLock;
class FeeAccount { private final ReentrantLock lock = new ReentrantLock(); private int paid = 0;
void payInstalment(int amount) { lock.lock(); try { System.out.println(" payInstalment: hold count " + lock.getHoldCount()); paid += amount; } finally { lock.unlock(); } }
void payFullFee(int[] instalments) { lock.lock(); try { System.out.println("payFullFee: hold count " + lock.getHoldCount()); for (int amount : instalments) { payInstalment(amount); // takes the same lock again } } finally { lock.unlock(); } }
int paid() { return paid; }
boolean isLocked() { return lock.isLocked(); }}
public class ReentrancyDemo { public static void main(String[] args) { FeeAccount account = new FeeAccount(); account.payFullFee(new int[] {25000, 25000}); System.out.println("Fee paid: " + account.paid()); System.out.println("Lock still held? " + account.isLocked()); }}payFullFee: hold count 1 payInstalment: hold count 2 payInstalment: hold count 2 Fee paid: 50000 Lock still held? false
What this code does
payFullFeeholds the lock (count 1) and callspayInstalment, which locks again (count 2) instead of blocking itself.- Each
unlock()brings the count down by one. After both methods finish, the count is 0 andisLocked()is false. getHoldCount()andisLocked()are for learning and debugging. Do not build program logic on them.
The word reentrant means a thread that already holds the lock can call lock() again without blocking itself. The lock keeps a hold count: each lock() adds one, each unlock() subtracts one. Other threads can take the lock only when the count is back to zero. So a method that holds the lock can safely call another method that takes the same lock. synchronized is reentrant in the same way.
Why unlock() always goes in finally
The lock, try, finally pattern calls lock(), puts the work in a try block, and calls unlock() in finally. A finally block runs whether the try block ends normally, returns early or throws an exception.
lock.lock(); // take the lock (before try)try { // read and change the shared data} finally { lock.unlock(); // always runs, even after an exception}Example 4 · An exception inside the lock, released by finally
import java.util.concurrent.locks.ReentrantLock;
class CustomerWallet { private final ReentrantLock lock = new ReentrantLock(); private int balance = 500;
void pay(int amount) { lock.lock(); try { if (amount <= 0) { throw new IllegalArgumentException("Amount must be positive: " + amount); } if (amount > balance) { throw new IllegalStateException("Not enough balance"); } balance -= amount; } finally { lock.unlock(); } }
int balance() { lock.lock(); try { return balance; } finally { lock.unlock(); } }
boolean isLocked() { return lock.isLocked(); }}
public class FinallyUnlockDemo { public static void main(String[] args) throws InterruptedException { CustomerWallet wallet = new CustomerWallet(); try { wallet.pay(-50); } catch (IllegalArgumentException e) { System.out.println("Payment failed: " + e.getMessage()); } System.out.println("Lock still held? " + wallet.isLocked());
Thread friend = new Thread(() -> wallet.pay(120), "friend"); friend.start(); friend.join(); System.out.println("Balance after friend pays: " + wallet.balance()); }}Payment failed: Amount must be positive: -50 Lock still held? false Balance after friend pays: 380
What this code does
pay(-50)throws in the middle of the critical section. Thefinallyblock still runs, so the lock is free again.- Because the lock was released, the
friendthread gets it at once and pays 120. Withoutfinally, that thread would wait forever. - The exception still reaches the caller.
finallyreleases the lock; it does not hide the error.
Without finally, an exception would jump straight past unlock(). The lock would stay held, and every other thread would wait for it forever. synchronized releases its lock automatically when an exception leaves the block; a Lock does not.
Call lock() just before try, not inside it. If lock() itself failed inside the try, the finally block would call unlock() on a lock you never took.
Fix the error
Make unlock safe
Read the error, then pick the line that fixes it.
Round 1 of 2
The method must always release the lock. Choose the line that replaces the closing brace.
Error
Main.java:2: error: 'try' without 'catch', 'finally' or resource declarations
What happens when unlock is forgotten
A forgotten unlock leaves the lock held with nobody to release it. This usually hides in an early return or a throw that skips the unlock() line.
Example 5 · Mistake: an early return that skips unlock()
import java.util.concurrent.locks.ReentrantLock;
class LeakyWallet { private final ReentrantLock lock = new ReentrantLock(); private int balance = 500;
boolean pay(int amount) { lock.lock(); if (amount > balance) { return false; // bug: leaves without unlock() } balance -= amount; lock.unlock(); return true; }
boolean isLocked() { return lock.isLocked(); }
int waitingThreads() { return lock.getQueueLength(); }}
public class ForgottenUnlockDemo { public static void main(String[] args) throws InterruptedException { LeakyWallet wallet = new LeakyWallet();
Thread first = new Thread(() -> System.out.println("student-1 paid 900? " + wallet.pay(900)), "student-1"); first.start(); first.join(); System.out.println("student-1 finished? " + !first.isAlive()); System.out.println("Lock still held? " + wallet.isLocked());
Thread second = new Thread(() -> wallet.pay(100), "student-2"); second.setDaemon(true); second.start(); second.join(300); // give up waiting after 300 ms while (second.getState() != Thread.State.WAITING) { Thread.sleep(1); // on a very busy machine, student-2 may need longer to reach lock() } System.out.println("student-2 state after 300 ms: " + second.getState()); System.out.println("Threads waiting for the lock: " + wallet.waitingThreads()); }}student-1 paid 900? false student-1 finished? true Lock still held? true student-2 state after 300 ms: WAITING Threads waiting for the lock: 1
What this code does
pay(900)takes the earlyreturn falsepath and never reachesunlock().student-1ends, but the lock stays held.student-2callslock()and waits forever in theWAITINGstate. No error is printed; the program would simply hang.- The demo only exits because
student-2is a daemon thread andmainstops waiting after 300 ms. The real fix is the lock, try, finally pattern.
The program does not crash and prints no error. The next thread that calls lock() simply waits forever, in the WAITING state. The lock stays held even after the thread that took it has finished, because a ReentrantLock does not know that its owner is gone. Only the thread that holds a lock may release it. If another thread calls unlock(), it gets an IllegalMonitorStateException, so you cannot "rescue" a stuck lock from outside.
Next step
Check your understanding
12 quick questions