jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea with assistance from members of JCP JSR-166 jaroslav@1890: * Expert Group and released to the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent.locks; jaroslav@1890: import java.util.*; jaroslav@1890: import java.util.concurrent.*; jaroslav@1890: import java.util.concurrent.atomic.*; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * A reentrant mutual exclusion {@link Lock} with the same basic jaroslav@1890: * behavior and semantics as the implicit monitor lock accessed using jaroslav@1890: * {@code synchronized} methods and statements, but with extended jaroslav@1890: * capabilities. jaroslav@1890: * jaroslav@1890: *

A {@code ReentrantLock} is owned by the thread last jaroslav@1890: * successfully locking, but not yet unlocking it. A thread invoking jaroslav@1890: * {@code lock} will return, successfully acquiring the lock, when jaroslav@1890: * the lock is not owned by another thread. The method will return jaroslav@1890: * immediately if the current thread already owns the lock. This can jaroslav@1890: * be checked using methods {@link #isHeldByCurrentThread}, and {@link jaroslav@1890: * #getHoldCount}. jaroslav@1890: * jaroslav@1890: *

The constructor for this class accepts an optional jaroslav@1890: * fairness parameter. When set {@code true}, under jaroslav@1890: * contention, locks favor granting access to the longest-waiting jaroslav@1890: * thread. Otherwise this lock does not guarantee any particular jaroslav@1890: * access order. Programs using fair locks accessed by many threads jaroslav@1890: * may display lower overall throughput (i.e., are slower; often much jaroslav@1890: * slower) than those using the default setting, but have smaller jaroslav@1890: * variances in times to obtain locks and guarantee lack of jaroslav@1890: * starvation. Note however, that fairness of locks does not guarantee jaroslav@1890: * fairness of thread scheduling. Thus, one of many threads using a jaroslav@1890: * fair lock may obtain it multiple times in succession while other jaroslav@1890: * active threads are not progressing and not currently holding the jaroslav@1890: * lock. jaroslav@1890: * Also note that the untimed {@link #tryLock() tryLock} method does not jaroslav@1890: * honor the fairness setting. It will succeed if the lock jaroslav@1890: * is available even if other threads are waiting. jaroslav@1890: * jaroslav@1890: *

It is recommended practice to always immediately jaroslav@1890: * follow a call to {@code lock} with a {@code try} block, most jaroslav@1890: * typically in a before/after construction such as: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890:  * class X {
jaroslav@1890:  *   private final ReentrantLock lock = new ReentrantLock();
jaroslav@1890:  *   // ...
jaroslav@1890:  *
jaroslav@1890:  *   public void m() {
jaroslav@1890:  *     lock.lock();  // block until condition holds
jaroslav@1890:  *     try {
jaroslav@1890:  *       // ... method body
jaroslav@1890:  *     } finally {
jaroslav@1890:  *       lock.unlock()
jaroslav@1890:  *     }
jaroslav@1890:  *   }
jaroslav@1890:  * }
jaroslav@1890:  * 
jaroslav@1890: * jaroslav@1890: *

In addition to implementing the {@link Lock} interface, this jaroslav@1890: * class defines methods {@code isLocked} and jaroslav@1890: * {@code getLockQueueLength}, as well as some associated jaroslav@1890: * {@code protected} access methods that may be useful for jaroslav@1890: * instrumentation and monitoring. jaroslav@1890: * jaroslav@1890: *

Serialization of this class behaves in the same way as built-in jaroslav@1890: * locks: a deserialized lock is in the unlocked state, regardless of jaroslav@1890: * its state when serialized. jaroslav@1890: * jaroslav@1890: *

This lock supports a maximum of 2147483647 recursive locks by jaroslav@1890: * the same thread. Attempts to exceed this limit result in jaroslav@1890: * {@link Error} throws from locking methods. jaroslav@1890: * jaroslav@1890: * @since 1.5 jaroslav@1890: * @author Doug Lea jaroslav@1890: */ jaroslav@1890: public class ReentrantLock implements Lock, java.io.Serializable { jaroslav@1890: private static final long serialVersionUID = 7373984872572414699L; jaroslav@1890: /** Synchronizer providing all implementation mechanics */ jaroslav@1890: private final Sync sync; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Base of synchronization control for this lock. Subclassed jaroslav@1890: * into fair and nonfair versions below. Uses AQS state to jaroslav@1890: * represent the number of holds on the lock. jaroslav@1890: */ jaroslav@1890: abstract static class Sync extends AbstractQueuedSynchronizer { jaroslav@1890: private static final long serialVersionUID = -5179523762034025860L; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Performs {@link Lock#lock}. The main reason for subclassing jaroslav@1890: * is to allow fast path for nonfair version. jaroslav@1890: */ jaroslav@1890: abstract void lock(); jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Performs non-fair tryLock. tryAcquire is jaroslav@1890: * implemented in subclasses, but both need nonfair jaroslav@1890: * try for trylock method. jaroslav@1890: */ jaroslav@1890: final boolean nonfairTryAcquire(int acquires) { jaroslav@1890: final Thread current = Thread.currentThread(); jaroslav@1890: int c = getState(); jaroslav@1890: if (c == 0) { jaroslav@1890: if (compareAndSetState(0, acquires)) { jaroslav@1890: setExclusiveOwnerThread(current); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: else if (current == getExclusiveOwnerThread()) { jaroslav@1890: int nextc = c + acquires; jaroslav@1890: if (nextc < 0) // overflow jaroslav@1890: throw new Error("Maximum lock count exceeded"); jaroslav@1890: setState(nextc); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected final boolean tryRelease(int releases) { jaroslav@1890: int c = getState() - releases; jaroslav@1890: if (Thread.currentThread() != getExclusiveOwnerThread()) jaroslav@1890: throw new IllegalMonitorStateException(); jaroslav@1890: boolean free = false; jaroslav@1890: if (c == 0) { jaroslav@1890: free = true; jaroslav@1890: setExclusiveOwnerThread(null); jaroslav@1890: } jaroslav@1890: setState(c); jaroslav@1890: return free; jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected final boolean isHeldExclusively() { jaroslav@1890: // While we must in general read state before owner, jaroslav@1890: // we don't need to do so to check if current thread is owner jaroslav@1890: return getExclusiveOwnerThread() == Thread.currentThread(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: final ConditionObject newCondition() { jaroslav@1890: return new ConditionObject(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: // Methods relayed from outer class jaroslav@1890: jaroslav@1890: final Thread getOwner() { jaroslav@1890: return getState() == 0 ? null : getExclusiveOwnerThread(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: final int getHoldCount() { jaroslav@1890: return isHeldExclusively() ? getState() : 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: final boolean isLocked() { jaroslav@1890: return getState() != 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Reconstitutes this lock instance from a stream. jaroslav@1890: * @param s the stream jaroslav@1890: */ jaroslav@1890: private void readObject(java.io.ObjectInputStream s) jaroslav@1890: throws java.io.IOException, ClassNotFoundException { jaroslav@1890: s.defaultReadObject(); jaroslav@1890: setState(0); // reset to unlocked state jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Sync object for non-fair locks jaroslav@1890: */ jaroslav@1890: static final class NonfairSync extends Sync { jaroslav@1890: private static final long serialVersionUID = 7316153563782823691L; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Performs lock. Try immediate barge, backing up to normal jaroslav@1890: * acquire on failure. jaroslav@1890: */ jaroslav@1890: final void lock() { jaroslav@1890: if (compareAndSetState(0, 1)) jaroslav@1890: setExclusiveOwnerThread(Thread.currentThread()); jaroslav@1890: else jaroslav@1890: acquire(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected final boolean tryAcquire(int acquires) { jaroslav@1890: return nonfairTryAcquire(acquires); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Sync object for fair locks jaroslav@1890: */ jaroslav@1890: static final class FairSync extends Sync { jaroslav@1890: private static final long serialVersionUID = -3000897897090466540L; jaroslav@1890: jaroslav@1890: final void lock() { jaroslav@1890: acquire(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Fair version of tryAcquire. Don't grant access unless jaroslav@1890: * recursive call or no waiters or is first. jaroslav@1890: */ jaroslav@1890: protected final boolean tryAcquire(int acquires) { jaroslav@1890: final Thread current = Thread.currentThread(); jaroslav@1890: int c = getState(); jaroslav@1890: if (c == 0) { jaroslav@1890: if (!hasQueuedPredecessors() && jaroslav@1890: compareAndSetState(0, acquires)) { jaroslav@1890: setExclusiveOwnerThread(current); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: else if (current == getExclusiveOwnerThread()) { jaroslav@1890: int nextc = c + acquires; jaroslav@1890: if (nextc < 0) jaroslav@1890: throw new Error("Maximum lock count exceeded"); jaroslav@1890: setState(nextc); jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: return false; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates an instance of {@code ReentrantLock}. jaroslav@1890: * This is equivalent to using {@code ReentrantLock(false)}. jaroslav@1890: */ jaroslav@1890: public ReentrantLock() { jaroslav@1890: sync = new NonfairSync(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates an instance of {@code ReentrantLock} with the jaroslav@1890: * given fairness policy. jaroslav@1890: * jaroslav@1890: * @param fair {@code true} if this lock should use a fair ordering policy jaroslav@1890: */ jaroslav@1890: public ReentrantLock(boolean fair) { jaroslav@1890: sync = fair ? new FairSync() : new NonfairSync(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the lock. jaroslav@1890: * jaroslav@1890: *

Acquires the lock if it is not held by another thread and returns jaroslav@1890: * immediately, setting the lock hold count to one. jaroslav@1890: * jaroslav@1890: *

If the current thread already holds the lock then the hold jaroslav@1890: * count is incremented by one and the method returns immediately. jaroslav@1890: * jaroslav@1890: *

If the lock is held by another thread then the jaroslav@1890: * current thread becomes disabled for thread scheduling jaroslav@1890: * purposes and lies dormant until the lock has been acquired, jaroslav@1890: * at which time the lock hold count is set to one. jaroslav@1890: */ jaroslav@1890: public void lock() { jaroslav@1890: sync.lock(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the lock unless the current thread is jaroslav@1890: * {@linkplain Thread#interrupt interrupted}. jaroslav@1890: * jaroslav@1890: *

Acquires the lock if it is not held by another thread and returns jaroslav@1890: * immediately, setting the lock hold count to one. jaroslav@1890: * jaroslav@1890: *

If the current thread already holds this lock then the hold count jaroslav@1890: * is incremented by one and the method returns immediately. jaroslav@1890: * jaroslav@1890: *

If the lock is held by another thread then the jaroslav@1890: * current thread becomes disabled for thread scheduling jaroslav@1890: * purposes and lies dormant until one of two things happens: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the lock is acquired by the current thread then the lock hold jaroslav@1890: * count is set to one. jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * jaroslav@1890: *

In this implementation, as this method is an explicit jaroslav@1890: * interruption point, preference is given to responding to the jaroslav@1890: * interrupt over normal or reentrant acquisition of the lock. jaroslav@1890: * jaroslav@1890: * @throws InterruptedException if the current thread is interrupted jaroslav@1890: */ jaroslav@1890: public void lockInterruptibly() throws InterruptedException { jaroslav@1890: sync.acquireInterruptibly(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the lock only if it is not held by another thread at the time jaroslav@1890: * of invocation. jaroslav@1890: * jaroslav@1890: *

Acquires the lock if it is not held by another thread and jaroslav@1890: * returns immediately with the value {@code true}, setting the jaroslav@1890: * lock hold count to one. Even when this lock has been set to use a jaroslav@1890: * fair ordering policy, a call to {@code tryLock()} will jaroslav@1890: * immediately acquire the lock if it is available, whether or not jaroslav@1890: * other threads are currently waiting for the lock. jaroslav@1890: * This "barging" behavior can be useful in certain jaroslav@1890: * circumstances, even though it breaks fairness. If you want to honor jaroslav@1890: * the fairness setting for this lock, then use jaroslav@1890: * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) } jaroslav@1890: * which is almost equivalent (it also detects interruption). jaroslav@1890: * jaroslav@1890: *

If the current thread already holds this lock then the hold jaroslav@1890: * count is incremented by one and the method returns {@code true}. jaroslav@1890: * jaroslav@1890: *

If the lock is held by another thread then this method will return jaroslav@1890: * immediately with the value {@code false}. jaroslav@1890: * jaroslav@1890: * @return {@code true} if the lock was free and was acquired by the jaroslav@1890: * current thread, or the lock was already held by the current jaroslav@1890: * thread; and {@code false} otherwise jaroslav@1890: */ jaroslav@1890: public boolean tryLock() { jaroslav@1890: return sync.nonfairTryAcquire(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the lock if it is not held by another thread within the given jaroslav@1890: * waiting time and the current thread has not been jaroslav@1890: * {@linkplain Thread#interrupt interrupted}. jaroslav@1890: * jaroslav@1890: *

Acquires the lock if it is not held by another thread and returns jaroslav@1890: * immediately with the value {@code true}, setting the lock hold count jaroslav@1890: * to one. If this lock has been set to use a fair ordering policy then jaroslav@1890: * an available lock will not be acquired if any other threads jaroslav@1890: * are waiting for the lock. This is in contrast to the {@link #tryLock()} jaroslav@1890: * method. If you want a timed {@code tryLock} that does permit barging on jaroslav@1890: * a fair lock then combine the timed and un-timed forms together: jaroslav@1890: * jaroslav@1890: *

if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
jaroslav@1890:      * 
jaroslav@1890: * jaroslav@1890: *

If the current thread jaroslav@1890: * already holds this lock then the hold count is incremented by one and jaroslav@1890: * the method returns {@code true}. jaroslav@1890: * jaroslav@1890: *

If the lock is held by another thread then the jaroslav@1890: * current thread becomes disabled for thread scheduling jaroslav@1890: * purposes and lies dormant until one of three things happens: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the lock is acquired then the value {@code true} is returned and jaroslav@1890: * the lock hold count is set to one. jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * jaroslav@1890: *

If the specified waiting time elapses then the value {@code false} jaroslav@1890: * is returned. If the time is less than or equal to zero, the method jaroslav@1890: * will not wait at all. jaroslav@1890: * jaroslav@1890: *

In this implementation, as this method is an explicit jaroslav@1890: * interruption point, preference is given to responding to the jaroslav@1890: * interrupt over normal or reentrant acquisition of the lock, and jaroslav@1890: * over reporting the elapse of the waiting time. jaroslav@1890: * jaroslav@1890: * @param timeout the time to wait for the lock jaroslav@1890: * @param unit the time unit of the timeout argument jaroslav@1890: * @return {@code true} if the lock was free and was acquired by the jaroslav@1890: * current thread, or the lock was already held by the current jaroslav@1890: * thread; and {@code false} if the waiting time elapsed before jaroslav@1890: * the lock could be acquired jaroslav@1890: * @throws InterruptedException if the current thread is interrupted jaroslav@1890: * @throws NullPointerException if the time unit is null jaroslav@1890: * jaroslav@1890: */ jaroslav@1890: public boolean tryLock(long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException { jaroslav@1890: return sync.tryAcquireNanos(1, unit.toNanos(timeout)); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Attempts to release this lock. jaroslav@1890: * jaroslav@1890: *

If the current thread is the holder of this lock then the hold jaroslav@1890: * count is decremented. If the hold count is now zero then the lock jaroslav@1890: * is released. If the current thread is not the holder of this jaroslav@1890: * lock then {@link IllegalMonitorStateException} is thrown. jaroslav@1890: * jaroslav@1890: * @throws IllegalMonitorStateException if the current thread does not jaroslav@1890: * hold this lock jaroslav@1890: */ jaroslav@1890: public void unlock() { jaroslav@1890: sync.release(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a {@link Condition} instance for use with this jaroslav@1890: * {@link Lock} instance. jaroslav@1890: * jaroslav@1890: *

The returned {@link Condition} instance supports the same jaroslav@1890: * usages as do the {@link Object} monitor methods ({@link jaroslav@1890: * Object#wait() wait}, {@link Object#notify notify}, and {@link jaroslav@1890: * Object#notifyAll notifyAll}) when used with the built-in jaroslav@1890: * monitor lock. jaroslav@1890: * jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: * @return the Condition object jaroslav@1890: */ jaroslav@1890: public Condition newCondition() { jaroslav@1890: return sync.newCondition(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries the number of holds on this lock by the current thread. jaroslav@1890: * jaroslav@1890: *

A thread has a hold on a lock for each lock action that is not jaroslav@1890: * matched by an unlock action. jaroslav@1890: * jaroslav@1890: *

The hold count information is typically only used for testing and jaroslav@1890: * debugging purposes. For example, if a certain section of code should jaroslav@1890: * not be entered with the lock already held then we can assert that jaroslav@1890: * fact: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890:      * class X {
jaroslav@1890:      *   ReentrantLock lock = new ReentrantLock();
jaroslav@1890:      *   // ...
jaroslav@1890:      *   public void m() {
jaroslav@1890:      *     assert lock.getHoldCount() == 0;
jaroslav@1890:      *     lock.lock();
jaroslav@1890:      *     try {
jaroslav@1890:      *       // ... method body
jaroslav@1890:      *     } finally {
jaroslav@1890:      *       lock.unlock();
jaroslav@1890:      *     }
jaroslav@1890:      *   }
jaroslav@1890:      * }
jaroslav@1890:      * 
jaroslav@1890: * jaroslav@1890: * @return the number of holds on this lock by the current thread, jaroslav@1890: * or zero if this lock is not held by the current thread jaroslav@1890: */ jaroslav@1890: public int getHoldCount() { jaroslav@1890: return sync.getHoldCount(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries if this lock is held by the current thread. jaroslav@1890: * jaroslav@1890: *

Analogous to the {@link Thread#holdsLock} method for built-in jaroslav@1890: * monitor locks, this method is typically used for debugging and jaroslav@1890: * testing. For example, a method that should only be called while jaroslav@1890: * a lock is held can assert that this is the case: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890:      * class X {
jaroslav@1890:      *   ReentrantLock lock = new ReentrantLock();
jaroslav@1890:      *   // ...
jaroslav@1890:      *
jaroslav@1890:      *   public void m() {
jaroslav@1890:      *       assert lock.isHeldByCurrentThread();
jaroslav@1890:      *       // ... method body
jaroslav@1890:      *   }
jaroslav@1890:      * }
jaroslav@1890:      * 
jaroslav@1890: * jaroslav@1890: *

It can also be used to ensure that a reentrant lock is used jaroslav@1890: * in a non-reentrant manner, for example: jaroslav@1890: * jaroslav@1890: *

jaroslav@1890:      * class X {
jaroslav@1890:      *   ReentrantLock lock = new ReentrantLock();
jaroslav@1890:      *   // ...
jaroslav@1890:      *
jaroslav@1890:      *   public void m() {
jaroslav@1890:      *       assert !lock.isHeldByCurrentThread();
jaroslav@1890:      *       lock.lock();
jaroslav@1890:      *       try {
jaroslav@1890:      *           // ... method body
jaroslav@1890:      *       } finally {
jaroslav@1890:      *           lock.unlock();
jaroslav@1890:      *       }
jaroslav@1890:      *   }
jaroslav@1890:      * }
jaroslav@1890:      * 
jaroslav@1890: * jaroslav@1890: * @return {@code true} if current thread holds this lock and jaroslav@1890: * {@code false} otherwise jaroslav@1890: */ jaroslav@1890: public boolean isHeldByCurrentThread() { jaroslav@1890: return sync.isHeldExclusively(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries if this lock is held by any thread. This method is jaroslav@1890: * designed for use in monitoring of the system state, jaroslav@1890: * not for synchronization control. jaroslav@1890: * jaroslav@1890: * @return {@code true} if any thread holds this lock and jaroslav@1890: * {@code false} otherwise jaroslav@1890: */ jaroslav@1890: public boolean isLocked() { jaroslav@1890: return sync.isLocked(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this lock has fairness set true. jaroslav@1890: * jaroslav@1890: * @return {@code true} if this lock has fairness set true jaroslav@1890: */ jaroslav@1890: public final boolean isFair() { jaroslav@1890: return sync instanceof FairSync; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the thread that currently owns this lock, or jaroslav@1890: * {@code null} if not owned. When this method is called by a jaroslav@1890: * thread that is not the owner, the return value reflects a jaroslav@1890: * best-effort approximation of current lock status. For example, jaroslav@1890: * the owner may be momentarily {@code null} even if there are jaroslav@1890: * threads trying to acquire the lock but have not yet done so. jaroslav@1890: * This method is designed to facilitate construction of jaroslav@1890: * subclasses that provide more extensive lock monitoring jaroslav@1890: * facilities. jaroslav@1890: * jaroslav@1890: * @return the owner, or {@code null} if not owned jaroslav@1890: */ jaroslav@1890: protected Thread getOwner() { jaroslav@1890: return sync.getOwner(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries whether any threads are waiting to acquire this lock. Note that jaroslav@1890: * because cancellations may occur at any time, a {@code true} jaroslav@1890: * return does not guarantee that any other thread will ever jaroslav@1890: * acquire this lock. This method is designed primarily for use in jaroslav@1890: * monitoring of the system state. jaroslav@1890: * jaroslav@1890: * @return {@code true} if there may be other threads waiting to jaroslav@1890: * acquire the lock jaroslav@1890: */ jaroslav@1890: public final boolean hasQueuedThreads() { jaroslav@1890: return sync.hasQueuedThreads(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries whether the given thread is waiting to acquire this jaroslav@1890: * lock. Note that because cancellations may occur at any time, a jaroslav@1890: * {@code true} return does not guarantee that this thread jaroslav@1890: * will ever acquire this lock. This method is designed primarily for use jaroslav@1890: * in monitoring of the system state. jaroslav@1890: * jaroslav@1890: * @param thread the thread jaroslav@1890: * @return {@code true} if the given thread is queued waiting for this lock jaroslav@1890: * @throws NullPointerException if the thread is null jaroslav@1890: */ jaroslav@1890: public final boolean hasQueuedThread(Thread thread) { jaroslav@1890: return sync.isQueued(thread); jaroslav@1890: } jaroslav@1890: jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the number of threads waiting to jaroslav@1890: * acquire this lock. The value is only an estimate because the number of jaroslav@1890: * threads may change dynamically while this method traverses jaroslav@1890: * internal data structures. This method is designed for use in jaroslav@1890: * monitoring of the system state, not for synchronization jaroslav@1890: * control. jaroslav@1890: * jaroslav@1890: * @return the estimated number of threads waiting for this lock jaroslav@1890: */ jaroslav@1890: public final int getQueueLength() { jaroslav@1890: return sync.getQueueLength(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a collection containing threads that may be waiting to jaroslav@1890: * acquire this lock. Because the actual set of threads may change jaroslav@1890: * dynamically while constructing this result, the returned jaroslav@1890: * collection is only a best-effort estimate. The elements of the jaroslav@1890: * returned collection are in no particular order. This method is jaroslav@1890: * designed to facilitate construction of subclasses that provide jaroslav@1890: * more extensive monitoring facilities. jaroslav@1890: * jaroslav@1890: * @return the collection of threads jaroslav@1890: */ jaroslav@1890: protected Collection getQueuedThreads() { jaroslav@1890: return sync.getQueuedThreads(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries whether any threads are waiting on the given condition jaroslav@1890: * associated with this lock. Note that because timeouts and jaroslav@1890: * interrupts may occur at any time, a {@code true} return does jaroslav@1890: * not guarantee that a future {@code signal} will awaken any jaroslav@1890: * threads. This method is designed primarily for use in jaroslav@1890: * monitoring of the system state. jaroslav@1890: * jaroslav@1890: * @param condition the condition jaroslav@1890: * @return {@code true} if there are any waiting threads jaroslav@1890: * @throws IllegalMonitorStateException if this lock is not held jaroslav@1890: * @throws IllegalArgumentException if the given condition is jaroslav@1890: * not associated with this lock jaroslav@1890: * @throws NullPointerException if the condition is null jaroslav@1890: */ jaroslav@1890: public boolean hasWaiters(Condition condition) { jaroslav@1890: if (condition == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) jaroslav@1890: throw new IllegalArgumentException("not owner"); jaroslav@1890: return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the number of threads waiting on the jaroslav@1890: * given condition associated with this lock. Note that because jaroslav@1890: * timeouts and interrupts may occur at any time, the estimate jaroslav@1890: * serves only as an upper bound on the actual number of waiters. jaroslav@1890: * This method is designed for use in monitoring of the system jaroslav@1890: * state, not for synchronization control. jaroslav@1890: * jaroslav@1890: * @param condition the condition jaroslav@1890: * @return the estimated number of waiting threads jaroslav@1890: * @throws IllegalMonitorStateException if this lock is not held jaroslav@1890: * @throws IllegalArgumentException if the given condition is jaroslav@1890: * not associated with this lock jaroslav@1890: * @throws NullPointerException if the condition is null jaroslav@1890: */ jaroslav@1890: public int getWaitQueueLength(Condition condition) { jaroslav@1890: if (condition == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) jaroslav@1890: throw new IllegalArgumentException("not owner"); jaroslav@1890: return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a collection containing those threads that may be jaroslav@1890: * waiting on the given condition associated with this lock. jaroslav@1890: * Because the actual set of threads may change dynamically while jaroslav@1890: * constructing this result, the returned collection is only a jaroslav@1890: * best-effort estimate. The elements of the returned collection jaroslav@1890: * are in no particular order. This method is designed to jaroslav@1890: * facilitate construction of subclasses that provide more jaroslav@1890: * extensive condition monitoring facilities. jaroslav@1890: * jaroslav@1890: * @param condition the condition jaroslav@1890: * @return the collection of threads jaroslav@1890: * @throws IllegalMonitorStateException if this lock is not held jaroslav@1890: * @throws IllegalArgumentException if the given condition is jaroslav@1890: * not associated with this lock jaroslav@1890: * @throws NullPointerException if the condition is null jaroslav@1890: */ jaroslav@1890: protected Collection getWaitingThreads(Condition condition) { jaroslav@1890: if (condition == null) jaroslav@1890: throw new NullPointerException(); jaroslav@1890: if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) jaroslav@1890: throw new IllegalArgumentException("not owner"); jaroslav@1890: return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a string identifying this lock, as well as its lock state. jaroslav@1890: * The state, in brackets, includes either the String {@code "Unlocked"} jaroslav@1890: * or the String {@code "Locked by"} followed by the jaroslav@1890: * {@linkplain Thread#getName name} of the owning thread. jaroslav@1890: * jaroslav@1890: * @return a string identifying this lock, as well as its lock state jaroslav@1890: */ jaroslav@1890: public String toString() { jaroslav@1890: Thread o = sync.getOwner(); jaroslav@1890: return super.toString() + ((o == null) ? jaroslav@1890: "[Unlocked]" : jaroslav@1890: "[Locked by thread " + o.getName() + "]"); jaroslav@1890: } jaroslav@1890: }