ReentrantLock.unLock():锁的释放
- public void unlock() {
- sync.release(1);//AQS
- }
AbstractQueuedSynchronizer.release()
- public final boolean release(int arg) {
- if (tryRelease(arg)) {//尝试释放锁,子类实现
- Node h = head;
- if (h != null && h.waitStatus != 0)
- unparkSuccessor(h);//唤醒后继节点
- return true;
- }
- return false;
- }
若 tryRelease(arg)释放锁成功(state==0);则考虑唤醒AQS中的下一个节点,前提:队列不为空,AQS队列的头结点需要锁(waitStatus!=0),如果头结点需要锁,就开始检测下一个继任节点是否需要锁操作。
waitStatus含义
ReentrantLock.Sync.tryRelease(int releases)
- protected final boolean tryRelease(int releases) {
- int c = getState() - releases;
- if (Thread.currentThread() != getExclusiveOwnerThread())//持有锁的线程不是当前线程,抛出异常。(线程锁只有拥有锁的线程才能释放)
- throw new IllegalMonitorStateException();
- boolean free = false;
- if (c == 0) {//state = 0:表示当前线程已经释放了锁,锁处于空闲状态.因为ReetrantLock可重入,maybe c>0
- free = true;
- setExclusiveOwnerThread(null);
- }
- setState(c);
- return free;
- }
AbstractQueuedSynchronizer.unparkSuccessor(Node node)
- private void unparkSuccessor(Node node) {
- /*
- * If status is negative (i.e., possibly needing signal) try
- * to clear in anticipation of signalling. It is OK if this
- * fails or if status is changed by waiting thread.
- */
- int ws = node.waitStatus;
- if (ws < 0)//当前node已经释放锁了,状态设置为0
- compareAndSetWaitStatus(node, ws, 0);
-
- /*
- * Thread to unpark is held in successor, which is normally
- * just the next node. But if cancelled or apparently null,
- * traverse backwards from tail to find the actual
- * non-cancelled successor.
- */
- //从头结点的下一个节点开始寻找继任节点,当且仅当继任节点的waitStatus<=0才是有效继任节点,否则将这些waitStatus>0(也就是CANCELLED的节点)从AQS队列中剔除
- //这里并没有从head->tail开始寻找,而是从tail->head寻找最后一个有效节点。
- //解释在这里 http://www.blogjava.net/xylz/archive/2010/07/08/325540.html#377512
- Node s = node.next;
- if (s == null || s.waitStatus > 0) {
- s = null;
- for (Node t = tail; t != null && t != node; t = t.prev)
- if (t.waitStatus <= 0)
- s = t;
- }
- if (s != null)
- LockSupport.unpark(s.thread);
- }
- 这里再一次把acquireQueued的过程找出来。对比unparkSuccessor,一旦头节点的继任节点被唤醒,那么继任节点就会尝试去获取锁(在acquireQueued中node就是有效的继任节点,p就是唤醒它的头结点),如果成功就会将头结点设置为自身,并且将头结点的前任节点清空,这样前任节点(已经过时了)就可以被GC释放了。
-
- final boolean acquireQueued(final Node node, int arg) {
- try {
- boolean interrupted = false;
- for (;;) {
- final Node p = node.predecessor();
- if (p == head && tryAcquire(arg)) {
- setHead(node);
- p.next = null; // help GC
- return interrupted;
- }
- if (shouldParkAfterFailedAcquire(p, node) &&
- parkAndCheckInterrupt())
- interrupted = true;
- }
- } catch (RuntimeException ex) {
- cancelAcquire(node);
- throw ex;
- }
- }
参考:http://www.blogjava.net/xylz/archive/2010/07/08/325540.html