非阻塞算法-ReentrantLock代码剖析之ReentrantLock.lock

本文深入剖析ReentrantLock的实现机制,包括线程调度、锁实现、中断和信号触发等内容。通过对ReentrantLock源码的逐行解读,帮助读者理解公平锁和非公平锁的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ReentrantLock是java.util.concurrent.locks中的一个可重入锁类。在高竞争条件下有更好的性能,且可以中断。深入剖析ReentrantLock的源码有助于我们了解线程调度,锁实现,中断,信号触发等底层机制,实现更好的并发程序。 

以下代码出自JDK1.6 

先来看ReentrantLock最常用的代码lock 
Java代码  收藏代码
  1. public void lock() {  
  2.         sync.lock();  
  3.     }  

很简单,直接调用了成员变量sync的lock方法。以下是sync的声明 
Java代码  收藏代码
  1. /** Synchronizer providing all implementation mechanics */  
  2.     private final Sync sync;  


从注释中我们可以看出sync提供了所有的实现机制,ReentrantLock只是简单执行了转发而已。 

下图是Sync的层次结构,Sync,FairSync和NonFairSync都是ReentrantLock的静态内部类。Sync 是一个抽象类,而FairSync和NonFairSync则是具体类,分别对应了公平锁和非公平锁。实际中公平锁吞吐量比非公平锁小很多,所以以下讨论若非特别说明均以非公平锁为例。 

 

在上图的类层次中,最核心的类当属 AbstractQueuedSynchronizer ,最重要的两个数据成员当前锁状态和等待链表都是由它来实现的。 

Java代码  收藏代码
  1. /** 
  2.      * Head of the wait queue, lazily initialized.  Except for 
  3.      * initialization, it is modified only via method setHead.  Note: 
  4.      * If head exists, its waitStatus is guaranteed not to be 
  5.      * CANCELLED. 
  6.      */  
  7.     private transient volatile Node head;  
  8.   
  9.     /** 
  10.      * Tail of the wait queue, lazily initialized.  Modified only via 
  11.      * method enq to add new wait node. 
  12.      */  
  13.     private transient volatile Node tail;  
  14.     /** 
  15.      * The synchronization state. 
  16.      */  
  17.     private volatile int state;  


state记录了当前锁被锁定的次数。如果为0则未被锁定。加锁通过更改状态实现,而更改状态主要由函数compareAndSetState实现。调用cas原语以保证操作的原子性,如果state值为expect,则更新为update值且返回true,否则不更改state且返回false. 

Java代码  收藏代码
  1. /** 
  2.      * Atomically sets synchronization state to the given updated 
  3.      * value if the current state value equals the expected value. 
  4.      * This operation has memory semantics of a <tt>volatile</tt> read 
  5.      * and write. 
  6.      * 
  7.      * @param expect the expected value 
  8.      * @param update the new value 
  9.      * @return true if successful. False return indicates that the actual 
  10.      *         value was not equal to the expected value. 
  11.      */  
  12. protected final boolean compareAndSetState(int expect, int update) {  
  13.         // See below for intrinsics setup to support this  
  14.         return unsafe.compareAndSwapInt(this, stateOffset, expect, update);  
  15.     }  

其中unsafe的类Unsafe为sun的非公开类sun.misc.Unsafe,有兴趣的可以反编译该类查看代码。 
而另一个重要的数据当前线程则是在 AbstractOwnableSynchronizer中。 

Java代码  收藏代码
  1. /** 
  2.      * The current owner of exclusive mode synchronization. 
  3.      */  
  4.     private transient Thread exclusiveOwnerThread;  


了解这些基本的数据结构后让我们来一探上面提到的 sync.lock()之究竟。以下是NonFairSync的lock函数。代码里中文注释均为本文作者添加。 

Java代码  收藏代码
  1. /** 
  2.          * Performs lock.  Try immediate barge, backing up to normal 
  3.          * acquire on failure. 
  4.          */  
  5. final void lock() {  
  6.             // 如果锁没有被任何线程锁定且加锁成功则设定当前线程为锁的拥有者  
  7.             // 如果锁已被当前线程锁定,则在acquire中将状态加1并返回  
  8.             if (compareAndSetState(01))  
  9.                 setExclusiveOwnerThread(Thread.currentThread());  
  10.             else  
  11.                 // 加锁失败,再次尝试加锁,失败则加入等待队列,禁用当前线程,直到被中断或有线程释放锁时被唤醒  
  12.                 acquire(1);  
  13.         }  


acquire方法在AbstractQueuedSynchronizer中定义。 

Java代码  收藏代码
  1. /** 
  2.      * Acquires in exclusive mode, ignoring interrupts.  Implemented 
  3.      * by invoking at least once {@link #tryAcquire}, 
  4.      * returning on success.  Otherwise the thread is queued, possibly 
  5.      * repeatedly blocking and unblocking, invoking {@link 
  6.      * #tryAcquire} until success.  This method can be used 
  7.      * to implement method {@link Lock#lock}. 
  8.      * 
  9.      * @param arg the acquire argument.  This value is conveyed to 
  10.      *        {@link #tryAcquire} but is otherwise uninterpreted and 
  11.      *        can represent anything you like. 
  12.      */  
  13. public final void acquire(int arg) {  
  14.     // 首先尝试获取锁,成功则直接返回  
  15.     // 否则将当前线程加入锁的等待队列并禁用当前线程  
  16.     // 直到线程被中断或者在锁为其它线程释放时唤醒  
  17.         if (!tryAcquire(arg) &&  
  18.             acquireQueued(addWaiter(Node.EXCLUSIVE), arg))  
  19.             selfInterrupt();  
  20.     }  


被tryAcquireNonFairSync override,直接调用 Sync.nonfairTryAcquire,代码如下 

Java代码  收藏代码
  1. /** 
  2.          * Performs non-fair tryLock.  tryAcquire is 
  3.          * implemented in subclasses, but both need nonfair 
  4.          * try for trylock method. 
  5.          */  
  6.         final boolean nonfairTryAcquire(int acquires) {  
  7.             final Thread current = Thread.currentThread();  
  8.             int c = getState();  
  9.             if (c == 0) {  
  10.                 // 如果锁空闲则尝试锁定,成功则设当前线程为锁拥有者  
  11.                 if (compareAndSetState(0, acquires)) {  
  12.                     setExclusiveOwnerThread(current);  
  13.                     return true;  
  14.                 }  
  15.             }  
  16.             // 若当前线程为锁拥有者则直接修改锁状态计数  
  17.             else if (current == getExclusiveOwnerThread()) {  
  18.                 int nextc = c + acquires;  
  19.                 if (nextc < 0// overflow  
  20.                     throw new Error("Maximum lock count exceeded");  
  21.                 setState(nextc);  
  22.                 return true;  
  23.             }  
  24.             // 尝试获取失败,返回  
  25.             return false;  
  26.         }  


在tryAcquire失败后则进行如下操作 

第一步调用AbstractQueuedSynchronizer.addWaiter将当前线程加入等待队列尾部,其中也涉及一些细微的同步操作及逻辑判断,就不详述了。有兴趣者可自行查看源码。 

Java代码  收藏代码
  1. /** 
  2.      * Creates and enqueues node for given thread and mode. 
  3.      * 
  4.      * @param current the thread 
  5.      * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared 
  6.      * @return the new node 
  7.      */  
  8.     private Node addWaiter(Node mode) {  
  9.         Node node = new Node(Thread.currentThread(), mode);  
  10.         // Try the fast path of enq; backup to full enq on failure  
  11.         Node pred = tail;  
  12.         if (pred != null) {  
  13.             node.prev = pred;  
  14.             if (compareAndSetTail(pred, node)) {  
  15.                 pred.next = node;  
  16.                 return node;  
  17.             }  
  18.         }  
  19.         enq(node);  
  20.         return node;  
  21.     }  


第二步调用AbstractQueuedSynchronizer.acquireQueued让线程进入禁用状态,并在每次被唤醒时尝试获取锁,失败则继续禁用线程。 

Java代码  收藏代码
  1. /** 
  2.      * Acquires in exclusive uninterruptible mode for thread already in 
  3.      * queue. Used by condition wait methods as well as acquire. 
  4.      * 
  5.      * @param node the node 
  6.      * @param arg the acquire argument 
  7.      * @return {@code true} if interrupted while waiting 
  8.      */  
  9.     final boolean acquireQueued(final Node node, int arg) {  
  10.         try {  
  11.             boolean interrupted = false;  
  12.             for (;;) {  
  13.                 // 如果当前线程是head的直接后继则尝试获取锁  
  14.                 // 这里不会和等待队列中其它线程发生竞争,但会和尝试获取锁且尚未进入等待队列的线程发生竞争。这是非公平锁和公平锁的一个重要区别。  
  15.                 final Node p = node.predecessor();  
  16.                 if (p == head && tryAcquire(arg)) {  
  17.                     setHead(node);  
  18.                     p.next = null// help GC  
  19.                     return interrupted;  
  20.                 }  
  21.                 // 如果不是head直接后继或获取锁失败,则检查是否要禁用当前线程  
  22.                 // 是则禁用,直到被lock.release唤醒或线程中断  
  23.                 if (shouldParkAfterFailedAcquire(p, node) &&  
  24.                     parkAndCheckInterrupt())  
  25.                     interrupted = true;  
  26.             }  
  27.         } catch (RuntimeException ex) {  
  28.             cancelAcquire(node);  
  29.             throw ex;  
  30.         }  
  31.     }  


AbstractQueuedSynchronizer. shouldParkAfterFailedAcquire做了一件很重要的事:根据状态对等待队列进行清理,并设置等待信号。 

这里需要先说明一下waitStatus,它是AbstractQueuedSynchronizer的静态内部类Node的成员变量,用于记录Node对应的线程等待状态.等待状态在刚进入队列时都是0,如果等待被取消则被设为Node.CANCELLED,若线程释放锁时需要唤醒等待队列里的其它线程则被置为Node.SIGNAL,还有一种状态Node.CONDITION这里先不讨论。 

Java代码  收藏代码
  1. /** waitStatus value to indicate thread has cancelled */  
  2.         static final int CANCELLED =  1;  
  3.         /** waitStatus value to indicate successor's thread needs unparking */  
  4.         static final int SIGNAL    = -1;  
  5.         /** waitStatus value to indicate thread is waiting on condition */  
  6.         static final int CONDITION = -2;  


AbstractQueuedSynchronizer.shouldParkAfterFailedAcquire实现如下 

Java代码  收藏代码
  1. /** 
  2.      * Checks and updates status for a node that failed to acquire. 
  3.      * Returns true if thread should block. This is the main signal 
  4.      * control in all acquire loops.  Requires that pred == node.prev 
  5.      * 
  6.      * @param pred node's predecessor holding status 
  7.      * @param node the node 
  8.      * @return {@code true} if thread should block 
  9.      */  
  10.     private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {  
  11.         int s = pred.waitStatus;  
  12.         if (s < 0)  
  13.             /* 
  14.              * This node has already set status asking a release 
  15.              * to signal it, so it can safely park 
  16.              */  
  17.             // 如果前置结点waitStatus已经被置为SIGNAL,则返回true,可以禁用线程  
  18.             return true;  
  19.         if (s > 0) {  
  20.             // 如果前置结果已被CALCEL,则移除。  
  21.             /* 
  22.              * Predecessor was cancelled. Skip over predecessors and 
  23.              * indicate retry. 
  24.              */  
  25.         do {  
  26.         node.prev = pred = pred.prev;  
  27.         } while (pred.waitStatus > 0);  
  28.         pred.next = node;  
  29.     }  
  30.         else  
  31.             /* 
  32.              * Indicate that we need a signal, but don't park yet. Caller 
  33.              * will need to retry to make sure it cannot acquire before 
  34.              * parking. 
  35.              */  
  36.             // 原子性将前置结点waitStatus设为SIGNAL  
  37.             compareAndSetWaitStatus(pred, 0, Node.SIGNAL);  
  38.         // 这里一定要返回false,有可能前置结点这时已经释放了锁,但因其 waitStatus在释放锁时还未被置为SIGNAL而未触发唤醒等待线程操作,因此必须通过return false来重新尝试一次获取锁  
  39.         return false;  
  40.     }  


AbstractQueuedSynchronizer.parkAndCheckInterrupt实现如下,很简单,直接禁用线程,并等待被唤醒或中断发生。对java中Thread.interrupted()都作了什么不甚了解的要做功课。 

这里线程即被堵塞,醒来时会重试获取锁,失败则继续堵塞。即使Thread.interrupted()也无法中断。那些想在等待时间过长时中断退出的线程可以调用ReentrantLoc.lockInterruptibly().其原理后继文章中会剖析。  

Java代码  收藏代码
  1. /** 
  2.      * Convenience method to park and then check if interrupted 
  3.      * 
  4.      * @return {@code true} if interrupted 
  5.      */  
  6.     private final boolean parkAndCheckInterrupt() {  
  7.         LockSupport.park(this);  
  8.         return Thread.interrupted();  
  9.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值