Module java.base

Class ReentrantLock

java.lang.Object
java.util.concurrent.locks.ReentrantLock
所有已实现的接口:
Serializable, Lock

public class ReentrantLock extends Object implements Lock, Serializable
具有与使用synchronized方法和语句访问的隐式监视器锁相同的基本行为和语义的可重入互斥Lock,但具有扩展功能。

ReentrantLock由最后成功锁定但尚未解锁的线程“拥有”。当锁未被另一个线程拥有时,调用lock的线程将返回,成功获取锁。如果当前线程已经拥有锁,则该方法将立即返回。可以使用isHeldByCurrentThread()getHoldCount()方法来检查这一点。

此类的构造函数接受一个可选的“公平性”参数。当设置为true时,在争用情况下,锁倾向于授予访问权给等待时间最长的线程。否则,此锁不保证任何特定的访问顺序。使用被许多线程访问的公平锁的程序可能显示较低的总体吞吐量(即,速度较慢;通常慢得多),但在获取锁的时间和保证不会饥饿方面具有较小的差异。但请注意,锁的公平性并不保证线程调度的公平性。因此,使用公平锁的众多线程之一可能连续多次获取它,而其他活动线程没有进展并且当前未持有锁。还请注意,未定时的tryLock()方法不遵守公平性设置。即使其他线程正在等待,如果锁可用,它也会成功。

建议实践是始终立即在调用lock后跟一个try块,通常在before/after构造中,例如:

 
 class X {
   private final ReentrantLock lock = new ReentrantLock();
   // ...

   public void m() {
     lock.lock();  // 阻塞直到条件成立
     try {
       // ... 方法体
     } finally {
       lock.unlock();
     }
   }
 }

除了实现Lock接口外,此类还定义了一些用于检查锁状态的publicprotected方法。其中一些方法仅对仪器化和监视有用。

此类的序列化行为与内置锁相同:反序列化的锁处于未锁定状态,而不管其在序列化时的状态如何。

此锁支持同一线程的最大2147483647个递归锁。尝试超过此限制将导致从锁定方法中抛出Error

自:
1.5
参见:
  • Constructor Details

    • ReentrantLock

      public ReentrantLock()
      创建ReentrantLock的实例。这等效于使用ReentrantLock(false)
    • ReentrantLock

      public ReentrantLock(boolean fair)
      使用给定的公平性策略创建ReentrantLock的实例。
      参数:
      fair - 如果此锁应使用公平排序策略,则为true
  • Method Details

    • lock

      public void lock()
      获取锁。

      如果此锁未被另一个线程持有,则获取锁并立即返回,将锁持有计数设置为一。

      如果当前线程已经持有此锁,则持有计数将增加一,并且方法将立即返回。

      如果锁被另一个线程持有,则当前线程将为了线程调度目的而被禁用,并处于休眠状态,直到获取锁为止,此时锁持有计数设置为一。

      指定者:
      lock 在接口 Lock
    • lockInterruptibly

      public void lockInterruptibly() throws InterruptedException
      除非当前线程被中断,否则获取锁。

      如果此锁未被另一个线程持有,则获取锁并立即返回,将锁持有计数设置为一。

      如果当前线程已经持有此锁,则持有计数将增加一,并且方法将立即返回。

      如果锁被另一个线程持有,则当前线程将为了线程调度目的而被禁用,并处于休眠状态,直到发生以下两种情况之一:

      • 当前线程获取锁;或
      • 其他线程中断当前线程。

      如果当前线程获取锁,则锁持有计数设置为一。

      如果当前线程:

      • 在进入此方法时设置了中断状态;或
      • 在获取锁时被中断
      则会抛出InterruptedException,并清除当前线程的中断状态。

      在此实现中,由于此方法是显式中断点,因此优先响应中断而不是正常或可重入地获取锁。

      指定者:
      lockInterruptibly 在接口 Lock
      抛出:
      InterruptedException - 如果当前线程被中断
    • tryLock

      public boolean tryLock()
      仅当调用时,如果此锁未被另一个线程持有,则获取锁。

      如果此锁未被另一个线程持有,则获取锁并立即返回,将锁持有计数设置为一。即使此锁已设置为使用公平排序策略,调用tryLock()将立即获取锁(如果可用),无论当前是否有其他线程正在等待锁。这种“闯入”行为在某些情况下可能很有用,尽管它破坏了公平性。如果要遵守此锁的公平性设置,则使用tryLock(0, TimeUnit.SECONDS),几乎等效(它还会检测中断)。

      如果当前线程已经持有此锁,则持有计数将增加一,并且方法将返回true

      如果锁被另一个线程持有,则此方法将立即返回false

      指定者:
      tryLock 在接口 Lock
      返回:
      如果锁空闲并被当前线程获取,或锁已被当前线程持有,则返回true;否则返回false
    • tryLock

      public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException
      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 true, setting the lock hold count to one. If this lock has been set to use a fair ordering policy then an available lock will not be acquired if any other threads are waiting for the lock. This is in contrast to the tryLock() method. If you want a timed tryLock that does permit barging on a fair lock then combine the timed and un-timed forms together:

       
       if (lock.tryLock() ||
           lock.tryLock(timeout, unit)) {
         ...
       }

      If the current thread already holds this lock then the hold count is incremented by one and the method returns true.

      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:

      • The lock is acquired by the current thread; or
      • Some other thread interrupts the current thread; or
      • The specified waiting time elapses

      If the lock is acquired then the value true is returned and the lock hold count is set to one.

      If the current thread:

      • has its interrupted status set on entry to this method; or
      • is interrupted while acquiring the lock,
      then InterruptedException is thrown and the current thread's interrupted status is cleared.

      If the specified waiting time elapses then the value false is returned. If the time is less than or equal to zero, the method will not wait at all.

      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.

      Specified by:
      tryLock in interface Lock
      Parameters:
      timeout - the time to wait for the lock
      unit - the time unit of the timeout argument
      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 acquired
      Throws:
      InterruptedException - if the current thread is interrupted
      NullPointerException - if the time unit is null
    • unlock

      public void unlock()
      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 IllegalMonitorStateException is thrown.

      Specified by:
      unlock in interface Lock
      Throws:
      IllegalMonitorStateException - if the current thread does not hold this lock
    • newCondition

      public Condition newCondition()
      Returns a Condition instance for use with this Lock instance.

      The returned Condition instance supports the same usages as do the Object monitor methods (wait, notify, and notifyAll) when used with the built-in monitor lock.

      • If this lock is not held when any of the Condition waiting or signalling methods are called, then an IllegalMonitorStateException is thrown.
      • When the condition waiting methods are called the lock is released and, before they return, the lock is reacquired and the lock hold count restored to what it was when the method was called.
      • If a thread is interrupted while waiting then the wait will terminate, an InterruptedException will be thrown, and the thread's interrupted status will be cleared.
      • Waiting threads are signalled in FIFO order.
      • The ordering of lock reacquisition for threads returning from waiting methods is the same as for threads initially acquiring the lock, which is in the default case not specified, but for fair locks favors those threads that have been waiting the longest.
      Specified by:
      newCondition in interface Lock
      Returns:
      the Condition object
    • getHoldCount

      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:

       
       class X {
         final ReentrantLock lock = new ReentrantLock();
         // ...
         public void m() {
           assert lock.getHoldCount() == 0;
           lock.lock();
           try {
             // ... method body
           } finally {
             lock.unlock();
           }
         }
       }
      Returns:
      the number of holds on this lock by the current thread, or zero if this lock is not held by the current thread
    • isHeldByCurrentThread

      public boolean isHeldByCurrentThread()
      Queries if this lock is held by the current thread.

      Analogous to the Thread.holdsLock(Object) method for built-in monitor locks, this method is typically used for debugging and testing. For example, a method that should only be called while a lock is held can assert that this is the case:

       
       class X {
         final ReentrantLock lock = new ReentrantLock();
         // ...
      
         public void m() {
             assert lock.isHeldByCurrentThread();
             // ... method body
         }
       }

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

       
       class X {
         final ReentrantLock lock = new ReentrantLock();
         // ...
      
         public void m() {
             assert !lock.isHeldByCurrentThread();
             lock.lock();
             try {
                 // ... method body
             } finally {
                 lock.unlock();
             }
         }
       }
      Returns:
      true if current thread holds this lock and false otherwise
    • isLocked

      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.
      Returns:
      true if any thread holds this lock and false otherwise
    • isFair

      public final boolean isFair()
      Returns true if this lock has fairness set true.
      Returns:
      true if this lock has fairness set true
    • getOwner

      protected Thread getOwner()
      Returns the thread that currently owns this lock, or null if not owned. When this method is called by a thread that is not the owner, the return value reflects a best-effort approximation of current lock status. For example, the owner may be momentarily null even if there are threads trying to acquire the lock but have not yet done so. This method is designed to facilitate construction of subclasses that provide more extensive lock monitoring facilities.
      Returns:
      the owner, or null if not owned
    • hasQueuedThreads

      public final boolean hasQueuedThreads()
      Queries whether any threads are waiting to acquire this lock. Note that because cancellations may occur at any time, a true return does not guarantee that any other thread will ever acquire this lock. This method is designed primarily for use in monitoring of the system state.
      Returns:
      true if there may be other threads waiting to acquire the lock
    • hasQueuedThread

      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 true return does not guarantee that this thread will ever acquire this lock. This method is designed primarily for use in monitoring of the system state.
      Parameters:
      thread - the thread
      Returns:
      true if the given thread is queued waiting for this lock
      Throws:
      NullPointerException - if the thread is null
    • getQueueLength

      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.
      Returns:
      the estimated number of threads waiting for this lock
    • getQueuedThreads

      protected Collection<Thread> getQueuedThreads()
      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.
      Returns:
      the collection of threads
    • hasWaiters

      public boolean hasWaiters(Condition condition)
      查询与此锁关联的给定条件上是否有任何线程正在等待。请注意,由于超时和中断可能随时发生,因此返回true并不保证将来的signal会唤醒任何线程。此方法主要设计用于监视系统状态。
      参数:
      condition - 条件
      返回:
      如果有任何等待的线程,则返回true
      抛出:
      IllegalMonitorStateException - 如果未持有此锁
      IllegalArgumentException - 如果给定条件与此锁不关联
      NullPointerException - 如果条件为null
    • getWaitQueueLength

      public int getWaitQueueLength(Condition condition)
      返回与此锁关联的给定条件上正在等待的线程数的估计值。请注意,由于超时和中断可能随时发生,因此该估计值仅作为实际等待线程数量的上限。此方法设计用于监视系统状态,而不是用于同步控制。
      参数:
      condition - 条件
      返回:
      估计的等待线程数
      抛出:
      IllegalMonitorStateException - 如果未持有此锁
      IllegalArgumentException - 如果给定条件与此锁不关联
      NullPointerException - 如果条件为null
    • getWaitingThreads

      protected Collection<Thread> getWaitingThreads(Condition condition)
      返回包含可能正在等待与此锁关联的给定条件的线程的集合。由于实际线程集可能在构造此结果时动态更改,因此返回的集合仅是最佳估计。返回的集合中的元素没有特定顺序。此方法旨在促进提供更广泛的条件监视功能的子类的构建。
      参数:
      condition - 条件
      返回:
      线程的集合
      抛出:
      IllegalMonitorStateException - 如果未持有此锁
      IllegalArgumentException - 如果给定条件与此锁不关联
      NullPointerException - 如果条件为null
    • toString

      public String toString()
      返回标识此锁及其锁状态的字符串。状态在括号中,包括字符串"Unlocked"或字符串"Locked by",后跟拥有线程的名称
      覆盖:
      toString 在类 Object
      返回:
      标识此锁及其锁状态的字符串