CKTIS / Java
ReentrantLock methods: acquisition, reentry, and conditions
Distinguish blocking `lock()` from both `tryLock()` overloads, balance every successful acquisition with `unlock()`, and use distinct conditions on the same lock.
Version: Java SE 21
Syntax
// Java SE 21 — instance methods of java.util.concurrent.locks.ReentrantLock
public void lock()
public void unlock()
public boolean tryLock()
public boolean tryLock(long timeout, java.util.concurrent.TimeUnit unit) throws InterruptedException
public java.util.concurrent.locks.Condition newCondition()
public int getHoldCount()In Java SE 21, java.util.concurrent.locks.ReentrantLock is a reentrant mutual-exclusion lock. ReentrantLock.lock waits if another thread owns the lock; interruption does not cancel that wait. The owner can acquire the same lock again without waiting. getHoldCount() counts the current thread's unmatched acquisitions, not waiting threads; 0 does not mean the lock is free.
ReentrantLock.unlock subtracts one hold and releases the lock only when the count reaches 0. A non-owner gets IllegalMonitorStateException. Enter a try immediately after each successful acquisition and put its matching unlock() in finally. Do not unlock on behalf of a failed or throwing attempt. When code needs both locks, every path must acquire them in the same order, such as gateLock before orderLock, and release them in reverse order.
With ReentrantLock.tryLock, the no-argument overload never waits: it returns false if another thread holds the lock, or true on acquisition, including reentry. It can bypass queued threads even on a fair lock. tryLock(timeout, unit) honors fairness when enabled, waits up to the specified duration (timeout <= 0 means no waiting), and returns false if it cannot acquire within that time. Interruption on entry or during acquisition causes InterruptedException and clears the interrupt status; unit == null is invalid and causes NullPointerException.
Each call to ReentrantLock.newCondition creates a separate Condition tied to the same lock. In a one-slot buffer, notEmpty is for consumers and notFull for producers. Calling signal() without owning that lock throws IllegalMonitorStateException. await() first checks the current thread's interrupt status. If it is already set, await() clears it and throws InterruptedException before checking ownership, without releasing the lock. Otherwise, await() throws IllegalMonitorStateException if the caller does not own the lock. If it proceeds to wait, it atomically releases the lock and reacquires it with the original hold count before the call completes. Test the state in a while loop because spurious wakeups are possible. Signal after changing the state, while still holding the lock; signal() does not release it.
Examples
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
private static final class Slot {
private final ReentrantLock lock = new ReentrantLock();
private final Condition notEmpty = lock.newCondition();
private final Condition notFull = lock.newCondition();
private Integer value;
void put(int item) throws InterruptedException {
lock.lock();
try {
while (value != null) {
notFull.await();
}
value = item;
notEmpty.signal();
} finally {
lock.unlock();
}
}
int take() throws InterruptedException {
lock.lock();
try {
while (value == null) {
notEmpty.await();
}
int item = value;
value = null;
notFull.signal();
return item;
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
ReentrantLock gateLock = new ReentrantLock();
ReentrantLock orderLock = new ReentrantLock(true);
System.out.println(orderLock.getHoldCount());
orderLock.lock();
try {
orderLock.lock();
try {
System.out.println(orderLock.getHoldCount());
} finally {
orderLock.unlock();
}
System.out.println(orderLock.getHoldCount());
if (orderLock.tryLock()) {
try {
System.out.println(orderLock.getHoldCount());
} finally {
orderLock.unlock();
}
}
System.out.println(orderLock.getHoldCount());
} finally {
orderLock.unlock();
}
System.out.println(orderLock.getHoldCount());
gateLock.lock();
try {
for (int attempt = 1; attempt <= 2; attempt++) {
if (!orderLock.tryLock(10, TimeUnit.MILLISECONDS)) {
System.out.println("timed " + attempt + ": timeout");
continue;
}
try {
System.out.println("timed " + attempt + ": acquired");
} finally {
orderLock.unlock();
}
}
} finally {
gateLock.unlock();
}
Slot slot = new Slot();
slot.put(42);
System.out.println("slot: " + slot.take());
}
}Result
0 2 1 2 1 0 timed 1: acquired timed 2: acquired slot: 42
Two `lock()` calls produce the first `2` after the initial `0`. One `unlock()` leaves `1`, and the owner's immediate `tryLock()` brings it back to `2`. The two remaining releases leave `1` and `0`. Both timed attempts target the same `orderLock` and succeed without contention. `put(42)` and `take()` use separate conditions on the slot's one lock; neither operation waits in this run.
Related lessons
- Java · Lesson 30 · Advanced · Version: 2
- Java · Lesson 54 · Intermediate · Version: 2
- Java · Lesson 58 · Intermediate · Version: 2