ReentrantLock起源
其实之前刚学习ReentrantLock的时候就觉得很奇怪,为什么有了synchronize却还需要ReentrantLock呢?
原来,在synchronize在jdk1.6以前都是一把重量级锁(需要调用系统函数实现的锁,比较耗费系统资源),为了能够使得锁更加轻量级,所以出现了ReentrantLock。(jdk1.5起才有ReentrantLock)
用法
ReentrantLock r = new ReentrantLock();//默认是非公平锁
//创建公平锁:ReentrantLock r = new ReentrantLock(true)
r.lock();
//需要同步的代码
r.unlock();
源码分析
//ReentrantLock的父类是Lock
public class ReentrantLock implements Lock, java.io.Serializable {
//有一个Sync成员变量
private final Sync sync;
...
Sync是啥?
//其实Sync就是一个AQS
abstract static class Sync extends AbstractQueuedSynchronizer
AbstractQueuedSynchronizer(aqs)又是啥?
我们看一下aqs的成员变量
volatile int waitStatus;//等待状态
volatile Node prev;//前一个节点
volatile Node next;//后一个节点
volatile Thread thread;//节点中存储的tread
可见aqs其实就是一个双向队列(其实是一个带头节点的双向队列),每个节点里面存储的是一个tread和和thread相关的状态值。所以说,Sync就是一个aqs双向队列。
ReentrantLock有公平锁和非公平锁之分,以下先研究公平锁的源码
先看一下r.lock()
//调用的是FairSync
static final class FairSync extends Sync {
final void lock() {
acquire(1);
}
......
}
深入看一下acquire(1)这个函数
public final void acquire(int arg) {
//tryAcquire()的return为true说明获取锁成功,否则说明获取锁失败,就会继续执行acquireQueued()
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
看一下tryAcquire()
protected final boolean tryAcquire(int acquires) {
//获取当前线程
final Thread current = Thread.currentThread();
//获取state数值,state默认值为0
int c = getState();
//判断是否有线程在使用锁,state为0说明没有线程在使用锁
if (c == 0) {
//hasQueuedPredecessors()判断队列中线程在排队
//compareAndSetState():进行了一次cas操作
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//如果持有锁的线程正是自己,state++;这里说明ReentrantLock是一把可重入锁
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
看下addWaiter()
private Node addWaiter(Node mode) {
//把单前节点封装成一个Node
Node node = new Node(Thread.currentThread(), mode);
//以下代码就是在队列尾部加上Node节点
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//如果队列没有初始化,则初始化
enq(node);
return node;
}
enq函数比较有趣,不断自旋初始化队列的head,初始化成功之后会将head.next设置为要插入的node,这里证明了这个aqs队列是带头结点的
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
acquireQueued()
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
//获取它的上一个节点,对比是不是head,是head的话说明他是排队的第一个,所以再次调用tryAcquire尝试获取锁。
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
//方便gc
p.next = null; // help GC
failed = false;
return interrupted;
}
//不是队列的排队中的第一个node或者获取锁失败,就会调用
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
shouldParkAfterFailedAcquire函数,这个函数其实就是将aqs队列中的插入node节点前一个节点的waitStatus状态值设置为-1(-1就是休眠状态)
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;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
//通过cas操作将前一个节点waitStatus设置为-1
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
parkAndCheckInterrupt用于将线程挂起,调用的是系统的park函数,线程会在这里进入休眠状态而不会继续往下执行
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
r.lock函数分析得差不多了。
总结一下就是:先获取state值(state值默认为0,为0时表示没有线程在使用锁,大于0的话面试有其他线程在使用锁),如果state等于0的话,就判断当前的线程是否是排队第一的那个线程(这里体现了公平锁),如果是的话就用cas操作修改state值为1。如果state大于0的话,就判断当前线程是不是占有锁的线程,如果是的话,state加1(这里体现了可重入锁)。如果state大于0的话,并且当前线程不是占有锁的线程,会调用addWaiter(Node node)函数将当前线程加入到aqs队列中,如果aqs队列为空则会调用enq(node)函数初始化aqs队列。如果state大于0的话,并且当前线程不是占有锁的线程,还会调用acquireQueued函数,acquireQueued函数会再次检查当前的node是不是排队中第一的那个node,如果是的话会再次获取锁,如果不是的话,会调用shouldParkAfterFailedAcquire函数将前缀节点的waistStaus改成-1,同时会调用LockSupport.park(this)将当前线程挂起。
下来来分析一下unlock函数
public void unlock() {
sync.release(1);
}
看一下sync.release(1)
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
//h.waitStatus不为0,说明h.waitStatus需要
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
再看一下tryRelease,可见tryRelease就是在帮state减1,如果state为0,说明没有线程在使用锁
protected final boolean tryRelease(int releases) {
//获取state值,将state减1
int c = getState() - releases;
//必须是当前持有锁的线程才能够释放锁,否则抛出异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//c为0,说明可以可以释放锁了
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
//设置state
setState(c);
return free;
}
看一下unparkSuccessor
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的waitStatus,说明他的下一个节点需要需要被唤醒了,就将当前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.
*/
Node s = node.next;
//如果下一个node的waitStatus并小于等于0,说明没有睡眠
if (s == null || s.waitStatus > 0) {
s = null;
//就会从尾部向头部找起,寻找离head最近的且waitStatus小于等于0的节点
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
//唤醒节点
if (s != null)
LockSupport.unpark(s.thread);
}
阅读源码到这里,我惊呆了,这个unlock源码居然找不到将aqs队列中已经排完队的node出队的代码,为啥?先打个问号,后续解决了回来继续更新。
该问题已经解决了,原来调用unlock函数的时候,不会调用任何的出队方法,出队列的方法是在lock函数的acquireQueued函数的cancelAcquire中。如果线程在acquireQueued中已经调用park函数导致线程挂起,所以不会执行到cancelAcquire函数,如果被调用在unlock中调用了unlock函数的话,会让阻塞在acquireQueued的函数会继续调用cancelAcquire函数,cancelAcquire函数就是一个让node出队列的方法了。
看一下cancelAcquire函数源码
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
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.
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
}
}