Java Reference ยท Concurrency
The Lock interface and ReentrantLock
Reference for java.util.concurrent.locks.Lock and ReentrantLock: lock/unlock in finally, tryLock, lockInterruptibly, fairness and Condition objects.
Lock is an explicit alternative to the synchronized keyword. ReentrantLock is its standard implementation: it offers the same mutual exclusion and memory visibility as a monitor, plus things monitors cannot do: trying to acquire without waiting, waiting with a timeout, waiting in a way that can be interrupted, optional fairness, and several wait queues (Condition objects) per lock.
The price is discipline. A synchronized block releases its monitor automatically; with a Lock you must call unlock() yourself, always in a finally block.
private final Lock lock = new ReentrantLock(); void update() { lock.lock(); try { // critical section } finally { lock.unlock(); // runs even if the section throws } }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public interface Lock public class ReentrantLock implements Lock, java.io.Serializable
| Method | Description |
|---|---|
lock() |
Acquires the lock, waiting as long as necessary. Not interruptible. |
lockInterruptibly() |
Acquires the lock but throws InterruptedException if the thread is interrupted while waiting. |
boolean tryLock() |
Acquires the lock only if it is free right now. |
boolean tryLock(long time, TimeUnit unit) |
Waits up to the timeout; interruptible. |
unlock() |
Releases one hold. Throws IllegalMonitorStateException if the caller does not hold the lock. |
Condition newCondition() |
A wait queue tied to this lock (await, signal, signalAll). |
new ReentrantLock(boolean fair) |
A fair lock serves the longest-waiting thread first; the default is unfair. |
getHoldCount(), isHeldByCurrentThread(), isLocked(), hasQueuedThreads() |
Monitoring (on ReentrantLock, not on Lock). |
Usage notes
unlock()belongs infinally. Calllock()immediately before thetry, not inside it, so that you never unlock a lock you failed to acquire.- Reentrant means the same thread can lock repeatedly; it must call
unlock()the same number of times. tryLock()avoids deadlock. Try to acquire several locks and back off (release what you hold) when one is busy, or give up after a timeout.- Fair locks cost throughput. Fairness prevents starvation but is much slower than the default barging lock. Note that
tryLock()without a timeout ignores fairness. Condition.await()must be in a loop that re-checks the predicate, for the same reasons asObject.wait(). The thread must hold the lock when callingawait,signalorsignalAll.- Conditions are separate queues. The buffer example uses
notFullandnotEmpty, so a producer never wakes another producer, whichnotifyAll()on a monitor cannot avoid. - Choose
synchronizedwhen it is enough. It is shorter, cannot leak a held lock, and since Java 24 does not pin virtual threads. Reach forReentrantLockwhen you needtryLock, timeouts, interruptible waits, fairness or multiple conditions. - Memory effects match monitors:
unlock()happens-before a laterlock()on the same lock.