Lock with the same basic
behavior and semantics as the implicit monitor lock accessed using
synchronized methods and statements, but with extended
capabilities.
A ReentrantLock is owned by the thread last
successfully locking, but not yet unlocking it. A thread invoking
lock will return, successfully acquiring the lock, when
the lock is not owned by another thread. The method will return
immediately if the current thread already owns the lock. This can
be checked using methods isHeldByCurrentThread, and getHoldCount.
The constructor for this class accepts an optional
fairness parameter. When set true, under
contention, locks favor granting access to the longest-waiting
thread. Otherwise this lock does not guarantee any particular
access order. Programs using fair locks accessed by many threads
may display lower overall throughput (i.e., are slower; often much
slower) than those using the default setting, but have smaller
variances in times to obtain locks and guarantee lack of
starvation. Note however, that fairness of locks does not guarantee
fairness of thread scheduling. Thus, one of many threads using a
fair lock may obtain it multiple times in succession while other
active threads are not progressing and not currently holding the
lock.
Also note that the untimed tryLock() method does not
honor the fairness setting. It will succeed if the lock
is available even if other threads are waiting.
It is recommended practice to always immediately
follow a call to lock with a try block, and
to always immediately call unlock as the
first statement in the finally block, as follows:
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // lock() as the last statement before the try block
try {
// ... method body
} finally {
lock.unlock(); // unlock() as the first statement in the finally block
}
}
}
In addition to implementing the Lock interface, this
class defines a number of public and protected
methods for inspecting the state of the lock. Some of these
methods are only useful for instrumentation and monitoring.
Serialization of this class behaves in the same way as built-in locks: a deserialized lock is in the unlocked state, regardless of its state when serialized.
This lock supports a maximum of 2147483647 recursive locks by
the same thread. Attempts to exceed this limit result in
Error throws from locking methods.
| Modifier and Type | Class and Description |
|---|---|
| pack-priv static class | ReentrantLock.
Sync object for fair locks |
| pack-priv static class | ReentrantLock.
Sync object for non-fair locks |
| pack-priv abstract static class | ReentrantLock.
Base of synchronization control for this lock. |
| Modifier and Type | Field and Description |
|---|---|
| private static final long | |
| private final ReentrantLock. |
| Access | Constructor and Description |
|---|---|
| public | |
| public | ReentrantLock(boolean
true if this lock should use a fair ordering policyCreates an instance of |
| Modifier and Type | Method and Description |
|---|---|
| public int | Returns: the number of holds on this lock by the current thread, or zero if this lock is not held by the current threadQueries the number of holds on this lock by the current thread. |
| protected Thread | Returns: the owner, ornull if not ownedReturns the thread that currently owns this lock, or
|
| protected Collection | Returns: the collection of threadsReturns a collection containing threads that may be waiting to acquire this lock. |
| public final int | Returns: the estimated number of threads waiting for this lockReturns an estimate of the number of threads waiting to acquire this lock. |
| protected Collection | Returns: the collection of threadsthe condition condition)Returns a collection containing those threads that may be waiting on the given condition associated with this lock. |
| public int | Returns: the estimated number of waiting threadsthe condition condition)Returns an estimate of the number of threads waiting on the given condition associated with this lock. |
| public final boolean | Returns: true if the given thread is queued waiting for this lockthe thread thread)Queries whether the given thread is waiting to acquire this lock. |
| public final boolean | Returns: true if there may be other threads waiting to
acquire the lockQueries whether any threads are waiting to acquire this lock. |
| public boolean | Returns: true if there are any waiting threadsthe condition condition)Queries whether any threads are waiting on the given condition associated with this lock. |
| public final boolean | Returns: true if this lock has fairness set trueReturns |
| public boolean | Returns: true if current thread holds this lock and
false otherwiseQueries if this lock is held by the current thread. |
| public boolean | Returns: true if any thread holds this lock and
false otherwiseQueries if this lock is held by any thread. |
| public void | |
| public void | lockInterruptibly()
Implements java. Acquires the lock unless the current thread is interrupted. |
| public Condition | Returns: the Condition objectImplements java. Returns a |
| public String | Returns: a string identifying this lock, as well as its lock stateOverrides java. Returns a string identifying this lock, as well as its lock state. |
| public boolean | Returns: true if the lock was free and was acquired by the
current thread, or the lock was already held by the current
thread; and false otherwiseImplements java. Acquires the lock only if it is not held by another thread at the time of invocation. |
| public boolean | Returns: true if the lock was free and was acquired by the
current thread, or the lock was already held by the current
thread; and false if the waiting time elapsed before
the lock could be acquiredthe time to wait for the lock timeout, TimeUnit the time unit of the timeout argument unit)Implements java. Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted. |
| public void |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID | |
| sync | back to summary |
|---|---|
| private final ReentrantLock. | |
| ReentrantLock | back to summary |
|---|---|
| public ReentrantLock() Creates an instance of | |
| ReentrantLock | back to summary |
|---|---|
| public ReentrantLock(boolean fair) Creates an instance of
| |
| getHoldCount | back to summary |
|---|---|
| public int getHoldCount() Queries the number of holds on this lock by the current thread. A thread has a hold on a lock for each lock action that is not matched by an unlock action. The hold count information is typically only used for testing and debugging purposes. For example, if a certain section of code should not be entered with the lock already held then we can assert that fact:
| |
| getOwner | back to summary |
|---|---|
| protected Thread getOwner() Returns the thread that currently owns this lock, or
| |
| getQueuedThreads | back to summary |
|---|---|
| protected Collection Returns a collection containing threads that may be waiting to acquire this lock. Because the actual set of threads may change dynamically while constructing this result, the returned collection is only a best-effort estimate. The elements of the returned collection are in no particular order. This method is designed to facilitate construction of subclasses that provide more extensive monitoring facilities.
| |
| getQueueLength | back to summary |
|---|---|
| public final int getQueueLength() Returns an estimate of the number of threads waiting to acquire this lock. The value is only an estimate because the number of threads may change dynamically while this method traverses internal data structures. This method is designed for use in monitoring system state, not for synchronization control.
| |
| getWaitingThreads | back to summary |
|---|---|
| protected Collection Returns a collection containing those threads that may be waiting on the given condition associated with this lock. Because the actual set of threads may change dynamically while constructing this result, the returned collection is only a best-effort estimate. The elements of the returned collection are in no particular order. This method is designed to facilitate construction of subclasses that provide more extensive condition monitoring facilities.
| |
| getWaitQueueLength | back to summary |
|---|---|
| public int getWaitQueueLength(Condition condition) Returns an estimate of the number of threads waiting on the given condition associated with this lock. Note that because timeouts and interrupts may occur at any time, the estimate serves only as an upper bound on the actual number of waiters. This method is designed for use in monitoring of the system state, not for synchronization control.
| |
| hasQueuedThread | back to summary |
|---|---|
| public final boolean hasQueuedThread(Thread thread) Queries whether the given thread is waiting to acquire this
lock. Note that because cancellations may occur at any time, a
| |
| hasQueuedThreads | back to summary |
|---|---|
| public final boolean hasQueuedThreads() Queries whether any threads are waiting to acquire this lock. Note that
because cancellations may occur at any time, a
| |
| hasWaiters | back to summary |
|---|---|
| public boolean hasWaiters(Condition condition) Queries whether any threads are waiting on the given condition
associated with this lock. Note that because timeouts and
interrupts may occur at any time, a
| |
| isFair | back to summary |
|---|---|
| public final boolean isFair() Returns
| |
| isHeldByCurrentThread | back to summary |
|---|---|
| public boolean isHeldByCurrentThread() Queries if this lock is held by the current thread. Analogous to the
It can also be used to ensure that a reentrant lock is used in a non-reentrant manner, for example:
| |
| isLocked | back to summary |
|---|---|
| public boolean isLocked() Queries if this lock is held by any thread. This method is designed for use in monitoring of the system state, not for synchronization control.
| |
| lock | back to summary |
|---|---|
| public void lock() Implements java. Acquires the lock. Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one. If the current thread already holds the lock then the hold count is incremented by one and the method returns immediately. If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one. | |
| lockInterruptibly | back to summary |
|---|---|
| public void lockInterruptibly() throws InterruptedException Implements java. Acquires the lock unless the current thread is interrupted. Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one. If the current thread already holds this lock then the hold count is incremented by one and the method returns immediately. If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of two things happens:
If the lock is acquired by the current thread then the lock hold count is set to one. If the current thread:
InterruptedException is thrown and the current thread's
interrupted status is cleared.
In this implementation, as this method is an explicit interruption point, preference is given to responding to the interrupt over normal or reentrant acquisition of the lock.
| |
| newCondition | back to summary |
|---|---|
| public Condition newCondition() Implements java. Returns a The returned
| |
| toString | back to summary |
|---|---|
| public String toString() Overrides java. Returns a string identifying this lock, as well as its lock state.
The state, in brackets, includes either the String
| |
| tryLock | back to summary |
|---|---|
| public boolean tryLock() Implements java. Acquires the lock only if it is not held by another thread at the time of invocation. Acquires the lock if it is not held by another thread and
returns immediately with the value If the current thread already holds this lock then the hold
count is incremented by one and the method returns If the lock is held by another thread then this method will return
immediately with the value
| |
| tryLock | back to summary |
|---|---|
| public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException Implements java. Acquires the lock if it is not held by another thread within the given waiting time and the current thread has not been interrupted. Acquires the lock if it is not held by another thread and returns
immediately with the value
If the current thread
already holds this lock then the hold count is incremented by one and
the method returns If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until one of three things happens:
If the lock is acquired then the value If the current thread:
InterruptedException is thrown and the current thread's
interrupted status is cleared.
If the specified waiting time elapses then the value In this implementation, as this method is an explicit interruption point, preference is given to responding to the interrupt over normal or reentrant acquisition of the lock, and over reporting the elapse of the waiting time.
| |
| unlock | back to summary |
|---|---|
| public void unlock() Implements java. Attempts to release this lock. If the current thread is the holder of this lock then the hold
count is decremented. If the hold count is now zero then the lock
is released. If the current thread is not the holder of this
lock then
| |
| Modifier and Type | Field and Description |
|---|---|
| private static final long |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| pack-priv final boolean | initialTryLock()
Implements abstract java. Acquires only if reentrant or queue is empty. |
| protected final boolean | tryAcquire(int acquires)
Overrides java. Acquires only if thread is first waiter or empty |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID Hides java. | |
| FairSync | back to summary |
|---|---|
| pack-priv FairSync() | |
| initialTryLock | back to summary |
|---|---|
| pack-priv final boolean initialTryLock() Implements abstract java. Acquires only if reentrant or queue is empty. | |
| tryAcquire | back to summary |
|---|---|
| protected final boolean tryAcquire(int acquires) Overrides java. Acquires only if thread is first waiter or empty | |
| Modifier and Type | Field and Description |
|---|---|
| private static final long |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| pack-priv final boolean | initialTryLock()
Implements abstract java. Checks for reentrancy and acquires if lock immediately available under fair vs nonfair rules. |
| protected final boolean | tryAcquire(int acquires)
Overrides java. Acquire for non-reentrant cases after initialTryLock prescreen |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID Hides java. | |
| NonfairSync | back to summary |
|---|---|
| pack-priv NonfairSync() | |
| initialTryLock | back to summary |
|---|---|
| pack-priv final boolean initialTryLock() Implements abstract java. Doc from java. Checks for reentrancy and acquires if lock immediately available under fair vs nonfair rules. Locking methods perform initialTryLock check before relaying to corresponding AQS acquire methods. | |
| tryAcquire | back to summary |
|---|---|
| protected final boolean tryAcquire(int acquires) Overrides java. Acquire for non-reentrant cases after initialTryLock prescreen | |
| Modifier and Type | Field and Description |
|---|---|
| private static final long |
| Access | Constructor and Description |
|---|---|
| pack-priv |
| Modifier and Type | Method and Description |
|---|---|
| pack-priv final int | |
| pack-priv final Thread | |
| pack-priv abstract boolean | initialTryLock()
Checks for reentrancy and acquires if lock immediately available under fair vs nonfair rules. |
| protected final boolean | isHeldExclusively()
Overrides java. Returns |
| pack-priv final boolean | |
| pack-priv final void | |
| pack-priv final void | |
| pack-priv final AbstractQueuedSynchronizer. | |
| private void | |
| pack-priv final boolean | |
| pack-priv final boolean | |
| protected final boolean | tryRelease(int releases)
Overrides java. Attempts to set the state to reflect a release in exclusive mode. |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID Hides java. | |
| Sync | back to summary |
|---|---|
| pack-priv Sync() | |
| getHoldCount | back to summary |
|---|---|
| pack-priv final int getHoldCount() | |
| getOwner | back to summary |
|---|---|
| pack-priv final Thread getOwner() | |
| initialTryLock | back to summary |
|---|---|
| pack-priv abstract boolean initialTryLock() Checks for reentrancy and acquires if lock immediately available under fair vs nonfair rules. Locking methods perform initialTryLock check before relaying to corresponding AQS acquire methods. | |
| isHeldExclusively | back to summary |
|---|---|
| protected final boolean isHeldExclusively() Overrides java. Doc from java. Returns The default implementation throws | |
| isLocked | back to summary |
|---|---|
| pack-priv final boolean isLocked() | |
| lock | back to summary |
|---|---|
pack-priv final void lock()
| |
| lockInterruptibly | back to summary |
|---|---|
pack-priv final void lockInterruptibly() throws InterruptedException
| |
| newCondition | back to summary |
|---|---|
| pack-priv final AbstractQueuedSynchronizer. | |
| readObject | back to summary |
|---|---|
| private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException Reconstitutes the instance from a stream (that is, deserializes it). | |
| tryLock | back to summary |
|---|---|
| pack-priv final boolean tryLock() Performs non-fair tryLock.
| |
| tryLockNanos | back to summary |
|---|---|
pack-priv final boolean tryLockNanos(long nanos) throws InterruptedException
| |
| tryRelease | back to summary |
|---|---|
| protected final boolean tryRelease(int releases) Overrides java. Doc from java. Attempts to set the state to reflect a release in exclusive mode. This method is always invoked by the thread performing release. The default implementation throws
| |