文章目录
ReentrantLock
代码的分析以非公平锁为例,有兴趣可以自己走一遍公平锁的流程。它们大致一样,只是在获取锁的时候有些许差别。
代码主要分为两部分
- 获取锁的过程 :锁状态修改、 等待队列、线程的挂起(WAITING 状态)、线程中断
- 释放锁的过程: 线程的唤醒
热身
ReentrantLock的重入锁的实现是通过内部子类Sync来实现的。Sync 继承自AQS,ReentrantLock通过操作Sync来获取和控制同步状态。
工具类的最大好处就是使用起来比较简单。比如如下操作:
public class LockReentrantDemo {
public static void main(String[] args) {
//定义一个重入锁
Lock lock=new ReentrantLock();
//开启两个线程
MyThread thread1= new MyThread(lock,"thread1....");
MyThread thread2= new MyThread(lock,"thread2...");
thread1.start();
thread2.start();
}
//定义一个内部类
static class MyThread extends Thread{
private Lock lock;
public MyThread(Lock lock,String name){
super(name);
this.lock=lock;
}
public void run() {
try {
lock.lock();
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) +".........."+Thread.currentThread().getName());
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
2019-08-08 16:01:25…thread1…
2019-08-08 16:01:27…thread2…
从上面可以看出 thread1 释放锁之后 thread2才能继续执行。
1. 公平锁和非公平锁
默认情况下就是非公平锁。非公平锁(就是插队)与公平锁的不同就在与不管队列中是否有节点在等待总是试图立即获取锁。
public ReentrantLock() {
sync = new NonfairSync();
}
调用有参构造函数,可以指定创建的是公平锁还是非公平锁。
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
2. 常用方法
ReentrantLock 中常用的方法就是lock,tryLock,unlock。暂时不涉及Condition
简单介绍一下它们的使用:
- lcok 尝试获取锁,获取成功则持有独占锁,重入则计数器加一,代码执行执行。否则进行AQS等待队列挂起
- tryLock 尝试获取锁,同上面不同的是会立即返回结果。获取到锁 返回true,未获取到返回false,如果是重入返回true。
- unlock 释放锁。如果该线程没有获取锁但是调用该方法则会抛出异常,否则重入计数器减一。
注意:
- tryLock 方法以非公平方式获取锁。
- tryLock(long timeout, TimeUnit unit) 的公平性和ReentrantLock 对象的构造有关。
ReentrantLock 继承结构
在AQS中存在一个变量 state,用来表示同步状态,不同的实现类含义可能不同。
在Reentrant中:
- state >=1 表示有锁。
- state= 1
- state >1 表示锁重入,即当前线程多次调用了lock 方法。
- state=0 ,表示无锁。
1. lock
多线程获取锁的过程:
- 判断当前锁状态,如果是无锁状态则尝试获取。获取成功返回,否则进入步骤2
- 未获取到锁就会将当前线程封装为Node节点,并加入等待队列挂起线程,直到其他线程调用unlock完全释放锁。
修改同步状态state(锁状态)
/**
* Acquires the lock.
*
* <p>Acquires the lock if it is not held by another thread and returns
* immediately, setting the lock hold count to one.
*
* <p>If the current thread already holds the lock then the hold
* count is incremented by one and the method returns immediately.
*
* <p>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.
*/
public void lock() {
sync.lock();
}
点击进入lock方法。会发现委派给内部类 Sync实现的。Sync有两个实现NonfairSync和FairSync。具体调用那个是根据创建ReentrantLock对象时是否指定锁类型确定的。
默认情况下就是非公平锁。非公平锁(就是插队)与公平锁的不同就在与不管队列中是否有节点在等待总是试图立即获取锁。
public ReentrantLock() {
sync = new NonfairSync();
}
非公平模式获取锁走下面的代码
NonfairSync.java
//NonfairSync.java
final void lock() {
//试图立即获取锁,获取成功则设置独占锁线程为当前线程。
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else //否则和公平锁一样调用AQS模板方法acquire()
acquire(1);
}
acquire方法继承自AQS,是一个模板方法是实现锁的核心方法。
该方法给我们规范了获取锁的操作步骤,之后的方法就是围绕这一功能展开的。
- 尝试获取锁,获取成功则跳出该方法
- 获取锁失败,则会将当前线程封装为Node节点并加入等待队列。
- 在等待队列中被挂起的线程被唤醒后,会尝试获取锁。获取成功将该节点设置为头结点,否则又会加入等待队列。
【AbstractQueuedSynchronizer.java】
/**
* Acquires in exclusive mode, ignoring interrupts. Implemented
* by invoking at least once {@link #tryAcquire},
* returning on success. Otherwise the thread is queued, possibly
* repeatedly blocking and unblocking, invoking {@link
* #tryAcquire} until success. This method can be used
* to implement method {@link Lock#lock}.
*
* @param arg the acquire argument. This value is conveyed to
* {@link #tryAcquire} but is otherwise uninterpreted and
* can represent anything you like.
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
tryAcquire 方法用于尝试获取锁,具体功能在子类中实现。当获取失败时则执行addWaiter方法将该线程加入到等待队列中。方法tryAcquire
是抽象方法,具体实现由子类提供,对于非公平锁,最终会调用 nonfairTryAcquire
【NonfairSync.java】
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();//获取锁状态 0表示无所状态,>=1,表示有锁状态
//如果此时没有线程持有锁,则立即尝试获取
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//是否当前线程已经获取到锁(重入)。如果是 将state锁计数加1
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
//java中整型都是有符号的,所以当数量较大时就会变为负数
//比如 byte: 127+1 => -128
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
等待队列
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
当获取锁失败的时候(tryAcquire 返回false),就会执行addWaiter(Node.EXCLUSIVE)方法,将当前线程包装为Node节点,并添加到等待队列中。
Node是AQS中的内部类,用于构建等待队列链表。它包含了以下重要属性
- waitStatus:等待状态,控制等待队列中节点(线程)的唤醒与挂起
- Node prev:指向上一节点
- Node next :指向下一节点
- thread : 竞争锁的线程
在AQS中 有两个重要的属性来指示队列的头尾节点。
- head; 指向等待队列头结点
- tail; 指向等待队列尾结点
刚开始 head= tail =null;
addWaiter 方法会执行以下逻辑操作:
- 队列为空。创建一个空节点作为头结点,并将创建的线程节点添加到队列中。
- 队列不为空,则直接将 线程节点加入到队列尾部。
AbstractQueuedSynchronizer.java
/**
* Creates and enqueues node for current thread and given mode.
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return the new node
*/
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
//队列不为空,则将该节点加入到队列的尾部
if (pred != null) {
node.prev = pred;
//将当前节点设置到队列尾部,设置失败则通过enq方法,自旋进行追加操作
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//否则 创建一个空的头结点,并将则将该节点加入到队列的尾部
enq(node);
return node;
}
AbstractQueuedSynchronizer.java
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
//创建空节点 tail = head =Node
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
注意:
- enq 方法返回的是当前节点的上一节点
- addWaiter 方法返回当前线程包装的节点
现在我们假设当前有三个线程要获取重入锁(A,B,C)。当前线程A已获取到了锁,然后线程B和线程C都执行到了addWaiter 方法。
- 此时队列中没有节点,head= tail = null。假设B线程先执行就会进入enq方法,此时执行代码 compareAndSetHead(new Node())创建一个空节点(node)。此时 tail = head = node。然后进入下一次循环执行compareAndSetTail(该方法线程安全),将B线程包装的节点添加到尾部。这时候链表结构就是 head = node -> threadB = tail
- 如果此时线程B已经插入等待队列,那么线程C节点直接添加到队列的尾部。如果此时头结点还没有创建或者 线程B的节点此时刚插入成功,那么都会执行enq 方法,最终加入队列中(head = node -> threadB->threadC=tail)。
线程B,C都加入后等待队列如下结构
线程挂起
线程节点加入到队列中后,就会执行acquireQueued
方法
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
下面的就是重头戏了,下面代码实现了节点线程的挂起和唤醒后重新获取锁的功能。
AbstractQueuedSynchronizer.java
/**
* Acquires in exclusive uninterruptible mode for thread already in
* queue. Used by condition wait methods as well as acquire.
*
* @param node the node
* @param arg the acquire argument
* @return {@code true} if interrupted while waiting
*/
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
//线程在挂起的过程中,是否调用了中断方法。
boolean interrupted = false;
for (;;) {
//获取上一个节点
final Node p = node.predecessor();
//如果上一个节点是头结点,则尝试获取锁
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//上一个节点不是head节点 或者 尝试获取锁失败则挂起当前线程。
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
//异常处理,取消节点
cancelAcquire(node);
}
}
以上面的节点为例。
节点B进入该方法,获取到上一节点 就是头结点(空节点)。
- 获取锁成功(线程A释放锁,并获取成功),将线程B的节点修改为头结点。线程获取锁后会继续执行 一些获取独占锁后的同步操作。
- 获取锁失败(线程A没有释放锁或者被其他线程抢先获取)。则尝试挂起B线程
shouldParkAfterFailedAcquire 方法用于更新节点的waitStatus
的值,如果当前节点的上一个节点的waitStatus == Node.SIGNAL
,则说明当前节点的线程可以安全的挂起。(因为调用unlock方法时,只用 waitStatus <0的节点,节点线程才会被唤醒)
/** Marker to indicate a node is waiting in shared mode */
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
static final Node EXCLUSIVE = null;
/** waitStatus value to indicate thread has cancelled */
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking */
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition */
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should
* unconditionally propagate
*/
static final int PROPAGATE = -3;
Node类中使用waitStatus 来控制节点的状态,定义了以下常量来标识不同状态:
- CANCELLED = 1;
- SIGNAL = -1; 标识当前节点的下一节点已经或者即将被挂起。当释放锁时需要唤醒改状态节点的下一节点。
- CONDITION = -2; condition队列节点初始状态
- PROPAGATE = -3;
- 0; AQS 等待队列节点的初始状态
AbstractQueuedSynchronizer.java
/**
* Checks and updates status for a node that failed to acquire.
* Returns true if thread should block. This is the main signal
* control in all acquire loops. Requires that pred == node.prev.
*
* @param pred node's predecessor holding status
* @param node the node
* @return {@code true} if thread should block
*/
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
// Node 节点的状态只有 CANCELLED 大于0 ,所以此时的操作用于取消线程执行
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
//暂时不涉及此处内容,只需要了解 头结点waitStatus永远不会大于零
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
节点状态的修改步骤:
- 线程B进入该方法,此时节点B的上一节点为Head节点waitStatus=0,会执行compareAndSetWaitStatus方法。修改成功后头节点状态 waitStatus=Node.SIGNAL,第一次循环方法返回false, 然后执行上面的acquireQueued 循环步骤。
- 如果再次循环依旧没有获取锁,则会又会执行shouldParkAfterFailedAcquire方法。此时头节点waitStatus=Node.SIGNAL 返回true。则会继续执行parkAndCheckInterrupt 挂起当前线程。
- 线程C进入acquireQueued 方法会执行上面相同的操作将它的上一节点(threadB)的waitStatus修改为 SIGNAL。如果B的节点状态已经修改waitStatus=Node.SIGNAL,那么直接返回true。
修改后的队列节点的状态值如下(假设此时unlock方法还未被调用,此时节点B和节点C都还在等待队列中):
shouldParkAfterFailedAcquire 返回true以后,就可以安心的挂起当前线程了。紧接着就会执行parkAndCheckInterrupt操作来挂起当前线程,该功能是通过方法LockSupport.park(this)来实现的。
AbstractQueuedSynchronizer.java
private final boolean parkAndCheckInterrupt() {
//挂起当前线程
LockSupport.park(this);
return Thread.interrupted();
}
这样当前线程就被挂起了,一直等待直到被唤醒。这样操作之后线程B和线程C都挂起了。
假设线程A执行完成调用了unlock方法并完全释放锁。这样线程B就会被唤醒,就会继续执行 接下来的代码( return Thread.interrupted()) 。这样又会继续执行acquireQueued 循环操作。此时线程A已经释放锁,如果此时没有新线程去竞争锁的话就是无锁状态,并且节点B(线程B)的上一个节点是头结点,这样线程B 通过tryAcquire方法获取锁成功,将B节点设置为头结点。线程B由此获取到了锁终止队列中的挂起,继续执行获取锁后的代码。
线程中断
线程获取被唤醒之后,并不会立即获取锁,而是先获取线程的中断状态。
因为线程被唤醒可能是以下原因:
- 调用了LockSupport.unpark(thread)方法
- 锁释放后调用的LockSupport.unpark()方法
- 其他线程调用LockSupport.unpark()方法
- 其他线程 中断了该线程(调用interrupt方法)。
因为如果在线程挂起的过程中,其他线程B调用了 threadB.interrupt()方法,后将线程B唤醒此时中断标志位为true。但是此时线程B还未获取到锁所以无法响应中断请求。当线程B成功获取到锁之后就可以响应之前的中断请求。
AbstractQueuedSynchronizer.java
private final boolean parkAndCheckInterrupt() {
//挂起线程
LockSupport.park(this);
//判断线程是否中断过,同时清除中断标志位
return Thread.interrupted();
}
在获取锁成功后会将这个中断状态返回。调用LockSupport.unpark()
方法唤醒的线程interrupted=false
,调用interrupt
方法导致线程被唤醒interrupted=true
因中断被唤醒的线程很有可能不能获取到锁,这样线程就又会被挂起,但是线程的中断状态已经被修改保存。所以当线程获取锁之后就会去响应中断。
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
如果线程被interrupt()方法唤醒并成功获取到锁,那么就会去响应中断。
AbstractQueuedSynchronizer.java
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
响应中断的方式很简单就是调用当前线程的interrupt
方法。当上述的代码执行完成之后 lock()代码执行完成,线程获取到了锁,然后继续上次退出的指令出执行。
AbstractQueuedSynchronizer.java
static void selfInterrupt() {
Thread.currentThread().interrupt();
}
对于线程中断的详细内容可以参考 博客:java线程随笔
节点取消
当执行acquireQueued 方法内部循环时,出现了异常
-
tryAcquire 方法抛出异常
else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc); return true; }
-
predecessor 获取上一节点
final Node predecessor() throws NullPointerException { Node p = prev; if (p == null) throw new NullPointerException(); else return p; }
-
其他异常 (InterruptedException,,,)
throw new InterruptedException();
那么就会执行取消节点操作
/**
* Cancels an ongoing attempt to acquire.
*
* @param node the node
*/
private void cancelAcquire(Node node) {
//注意该节点是线程节点
//这也是为什么头节点的waitStatus不可能为 1(CANCELLED)
// Ignore if node doesn't exist
if (node == null)
return;
//被取消的节点是能再执行线程任务,所以置位null
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
//循环,跳过waitStatus=CANCELLED 的节点。
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// predNext is the apparent node to unsplice. CASes below will
// fail if not, in which case, we lost race vs another cancel
// or signal, so no further action is necessary.
Node predNext = pred.next;
// Can use unconditional write instead of CAS here.
// After this atomic step, other Nodes can skip past us.
// Before, we are free of interference from other threads.
//设置节点状态为取消(1)
node.waitStatus = Node.CANCELLED;
// If we are the tail, remove ourselves.
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
int ws;
if (pred != head &&
((ws = pred.waitStatus) == Node.SIGNAL ||
(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
pred.thread != null) {
Node next = node.next;
if (next != null && next.waitStatus <= 0)
compareAndSetNext(pred, predNext, next);
} else {
unparkSuccessor(node);
}
node.next = node; // help GC
}
}
2.unlock
唤醒线程的功能就是在unlock中数实现的。相较于获取锁而言,释放锁的代码和逻辑更清晰。
下面还是以非公平锁展开。
/**
* Attempts to release this lock.
*
* <p>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 {@link IllegalMonitorStateException} is thrown.
*
* @throws IllegalMonitorStateException if the current thread does not
* hold this lock
*/
public void unlock() {
sync.release(1);
}
release 方法也是一个模板方法。
主要是以下逻辑:
- 当重入了多次的时候,会将重入计数次数减一
- 释放锁成功(state==0)则会唤醒等待队列中头节点的下一节点中的线程
AbstractQueuedSynchronizer.java
/**
* Releases in exclusive mode. Implemented by unblocking one or
* more threads if {@link #tryRelease} returns true.
* This method can be used to implement method {@link Lock#unlock}.
*
* @param arg the release argument. This value is conveyed to
* {@link #tryRelease} but is otherwise uninterpreted and
* can represent anything you like.
* @return the value returned from {@link #tryRelease}
*/
public final boolean release(int arg) {
// true: 重入锁已经全部释放。此时会唤醒等待队列中的线程节点
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
// 唤醒下一节点
unparkSuccessor(h);
return true;
}
return false;
}
Sync继承了AQS,修改锁状态state,当state==0是说明为无锁状态。state>1 :说明当前线程多次获取了锁(锁重入)
同tryQcquire 方法一样 tryRelease方法需要在子类中实现具体功能。
Sync.java
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
//不合法的状态,为获取锁的线程试图调用unlock方法会抛出该异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
//锁计数为0,exclusiveThread = null
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
正是因为 一次unlock操作只会 state–,所以lock和unlock必须成对出现,而且unlock释放锁操作需要放在finally代码块中执行。
锁释放成功后,就会唤醒等待队列中 头节点的下一节点中的线程。以上面等待队列为例,此时会唤醒节点B。
AbstractQueuedSynchronizer.java
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)
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.
*/
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);
}
看似compareAndSetWaitStatus
方法没有起到任何作用,操作只是将waitStatus修改为0(此时值为 -1)。为什么要多次一举呢?? AQS是模板工具类,应当具有良好的扩展性、通用性和可读性。所以waitStatus 的状态才有很多个用于明确节点所处状态。在ReentrantLock等待队列中SIGNAL状态没有起到什么实质作用,但是在Condition队列,CountDownLatch 中就真正用到了 SIGNAL状态。
线程被唤醒之后,被唤醒的线程就会紧接着上面的操作向下执行。
final boolean acquireQueued(final Node node, int arg) {
//.................................
boolean interrupted = false;
for (;;) {
//获取上一个节点
final Node p = node.predecessor();
//如果上一个节点是头结点,则尝试获取锁
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//上一个节点不是head节点 或者 尝试获取锁失败则挂起当前线程。
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
//...........................
}
总结
注意:
-
关于一些术语的问题
有些术语用的不是特别准确。比如线程挂起的问题,我其实不太清楚LockSupport.park()方法调用后具体应该用什么术语描述比较准确。根据java文档中给出的注释来说,说线程等待应该更准确些,但是语义上好像又没有那么通畅。所以我用的是线程挂起/** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> */ WAITING
-
上面介绍的ReentrantLock 获取锁的流程。如果是考虑到Condition队列就要复杂些了。
小结:
- lock、unlock方法必须成对出现
- unlock 方法应当放在 finally代码块中,以保证锁一定会释放。
下面重新回顾获取锁的流程:
- 查看当前锁标识,如果是无锁状态,则通过CAS操作原子获取锁。
- 当前已经是有锁状态
- 获取锁的线程和当前线程是同一个,则重入 state++
- 如果不同则将线程包装为Node节点加入到队列中,并将符合条件的线程挂起。
不是时序图的时序图
释放锁步骤:
- 检查锁状态和拥有锁的线程。
- 重入则将state–,否则唤醒等待队列中的下一节点中的线程。
AQS
Provides a framework for implementing blocking locks and related synchronizers (semaphores, events, etc) that rely on first-in-first-out (FIFO) wait queues
AbstractQueuedSynchronizer(AQS) 是一个基于先进先出队列(FIFO)的同步框架,框架用于实现 阻塞锁和一些相关的同步器。
AQS会维护一个同步状态(state),在不同的实现类中有不同的含义。 JDK 6中AQS被广泛使用,基于AQS实现的同步器包括:ReentrantLock、Semaphore、ReentrantReadWriteLock、CountDownLatch和FutureTask。
AQS中有几个重要的属性
- Thread exclusiveOwnerThread:保存当前获取锁的线程。该属性继承自AbstractOwnableSynchronizer
- int state : 同步状态。不同实现类中state的含义也是不同的。
- CountDownLatch: 计数器
- ReentrantLock: 重入锁,也可以说是锁计数器
- Node tail: 指向队列尾部节点
- Node head:指向队列的头部节点
- volatile Node prev;
- volatile Node next;
Node
AQS中使用内部类Node来维护先进先出的等待队列。
构造函数
//用于创建头节点
Node() { // Used to establish initial head or SHARED marker
}
// 调用addWaiter方法用于添加一个节点
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
//构造Condition 队列中的节点
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
waitStatus
waitStatus 设置节点的状态 用来控制节点的挂起,唤醒和移除。
/** waitStatus value to indicate thread has cancelled */
//节点取消
static final int CANCELLED = 1;
/** waitStatus value to indicate successor's thread needs unparking */
//表示当前节点下一节点可以安全挂起
static final int SIGNAL = -1;
/** waitStatus value to indicate thread is waiting on condition */
//condition 队列中的初始状态
static final int CONDITION = -2;
/**
* waitStatus value to indicate the next acquireShared should unconditionally propagate
*/
//
static final int PROPAGATE = -3;
/**
* Status field, taking on only the values:
* SIGNAL: The successor of this node is (or will soon be)
* blocked (via park), so the current node must
* unpark its successor when it releases or
* cancels. To avoid races, acquire methods must
* first indicate they need a signal,
* then retry the atomic acquire, and then,
* on failure, block.
* CANCELLED: This node is cancelled due to timeout or interrupt.
* Nodes never leave this state. In particular,
* a thread with cancelled node never again blocks.
* CONDITION: This node is currently on a condition queue.
* It will not be used as a sync queue node
* until transferred, at which time the status
* will be set to 0. (Use of this value here has
* nothing to do with the other uses of the
* field, but simplifies mechanics.)
* PROPAGATE: A releaseShared should be propagated to other
* nodes. This is set (for head node only) in
* doReleaseShared to ensure propagation
* continues, even if other operations have
* since intervened.
* 0: None of the above
*
* The values are arranged numerically to simplify use.
* Non-negative values mean that a node doesn't need to
* signal. So, most code doesn't need to check for particular
* values, just for sign.
*
* The field is initialized to 0 for normal sync nodes, and
* CONDITION for condition nodes. It is modified using CAS
* (or when possible, unconditional volatile writes).
*/
volatile int waitStatus;
其他
thread: 保存操作的线程
/** Marker to indicate a node is waiting in shared mode */
//共享锁模式
static final Node SHARED = new Node();
/** Marker to indicate a node is waiting in exclusive mode */
//独占锁模式
static final Node EXCLUSIVE = null;
/**
* Link to predecessor node that current node/thread relies on
* for checking waitStatus. Assigned during enqueuing, and nulled
* out (for sake of GC) only upon dequeuing. Also, upon
* cancellation of a predecessor, we short-circuit while
* finding a non-cancelled one, which will always exist
* because the head node is never cancelled: A node becomes
* head only as a result of successful acquire. A
* cancelled thread never succeeds in acquiring, and a thread only
* cancels itself, not any other node.
*/
volatile Node prev;
/**
* Link to the successor node that the current node/thread
* unparks upon release. Assigned during enqueuing, adjusted
* when bypassing cancelled predecessors, and nulled out (for
* sake of GC) when dequeued. The enq operation does not
* assign next field of a predecessor until after attachment,
* so seeing a null next field does not necessarily mean that
* node is at end of queue. However, if a next field appears
* to be null, we can scan prev's from the tail to
* double-check. The next field of cancelled nodes is set to
* point to the node itself instead of null, to make life
* easier for isOnSyncQueue.
*/
volatile Node next;
/**
* The thread that enqueued this node. Initialized on construction and nulled out after use.
*/
//进入此节点队列的线程
volatile Thread thread;
/**
* Link to next node waiting on condition, or the special
* value SHARED. Because condition queues are accessed only
* when holding in exclusive mode, we just need a simple
* linked queue to hold nodes while they are waiting on
* conditions. They are then transferred to the queue to
* re-acquire. And because conditions can only be exclusive,
* we save a field by using special value to indicate shared
* mode.
*/
//Condition 队列用于指向下一节点
Node nextWaiter;
/**
* Returns true if node is waiting in shared mode.
*/
//是否是共享模式(共享锁)
final boolean isShared() {
return nextWaiter == SHARED;
}
/**
* Returns previous node, or throws NullPointerException if null.
* Use when predecessor cannot be null. The null check could
* be elided, but is present to help the VM.
*
* @return the predecessor of this node
*/
//获取当前节点的上一节点
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
}
队列
初始状态,head=tail = null
当有线程进入队列时,会先创建头节点