浅谈Lock锁(AQS,独占锁情况下ReentrantLock源码分析)
- Lock锁的介绍
在Lock接口出现之前,java是使用synchronized来实现锁的功能的,但是在JDK5之后,JUC包提供了Lock锁的接口,以供显式的获取锁和释放锁,拥有了锁获取和释放的可操作性,可中断性,超时获取锁等多种同步特性
通过这种方式来获取锁和释放锁
- Lock接口下的功能
//获得锁
void lock();
//可中断的获取锁,这个方法可以响应中断,锁获取中可以中断当前线程
void lockInterruptibly() throws InterruptedException;
//尝试非阻塞的获取锁
boolean tryLock();
//超时的获取锁
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
//释放锁
void unlock();
//生成一个等待通知的组件
Condition newCondition();
- AQS的方法
模板方法可以分为三类,查询同步队列中的等待线程状态、共享式获取与释放同步状态、独占式获取与释放同步状态
AQS内部主要就是维护了一个同步队列
以Node节点来维护这么一个FIFO的CLH链表队列
使其抽象的生成了这么一个队列
- 借助ReentrantLock源码分析其实现学习AQS
非公平锁实现
首先我们来看ReentrantLock的构造方法
//这里可以看见,对于无参构造创建ReentrantLock就是默认使用了非公平锁的设置
public ReentrantLock() {
sync = new NonfairSync();
}
//初始的时候可以对使用公平锁还是非公平锁进行设置
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
//这里就是对非公平锁的具体加锁
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
//这里的lock方法就是用来加锁的方法
final void lock() {
//这里首先是判断是否能使用CAS的方法变更状态
//成功就代表加锁成功
if (compareAndSetState(0, 1))
//设置独有的线程是当前线程
setExclusiveOwnerThread(Thread.currentThread());
else
//这里就是加锁失败,进入acquire方法
acquire(1);
}
//这里是进行尝试获取锁
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
public final void acquire(int arg) {
//这里会再次尝试加锁,在这里加锁失败之后,才会将其加入阻塞的FIFO队列
if (!tryAcquire(arg) &&
//Node.EXCLUSIVE 指示节点正在以独占模式等待的标记
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
protected final boolean tryAcquire(int acquires) {
//这里尝试获取当前线程
final Thread current = Thread.currentThread();
//这里获取同步状态
int c = getState();
if (c == 0) {
//这里判断队列中有没有等待的线程
if (//CAS操作尝试变更状态
compareAndSetState(0, acquires)) {
//这里设置独占的的线程为当前线程,并返回true
setExclusiveOwnerThread(current);
return true;
}
}
//在这里判断的是当前线程是不是现在独占的线程
//因为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;
}
//这里是前置尝试加锁失败之后,会将当前线程加入到等待队列中
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节点添加到队列队尾
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//如果当前队列还没有进行初始化
//就调用enq方法创建
enq(node);
return node;
}
//这里的作用就是自旋的将该节点插入到队列中
//若队列没有经过初始化。就将节点作为head节点,初始化好队列
//若队列已经初始化好了,那么就将节点插在队尾
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
//这里就是生成了一个空Node作为head节点,然后头尾指向一个
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
//这里就是以排他的方式不断地获取已经在FIFO队列的线程,用于条件等待和方法获取
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
//以自旋的方式操作
for (;;) {
//获取当前节点的前置节点
final Node p = node.predecessor();
//判断前置节点是不是头结点,如果是头结点的话,代表当前节点可以尝试获取锁
//获取成功的话,就把当前节点设置为头结点,并将原来的节点GC
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//这里就是根据前驱结点来判断当前节点是否能休息
if (shouldParkAfterFailedAcquire(p, node) &&
//阻塞操作,在这里正常代码获取不到锁就被park住,等待唤醒
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
//线程park阻塞时,这时线程被中断,会抛异常,这个时候就进入finally中
//也就是这里变更node状态
if (failed)
cancelAcquire(node);
}
}
//这里可以做一段总结,首先我拿到前驱结点的状态
//如果是signal状态,也就是前置节点有责任唤醒后置节点的状态,那么就被阻塞住
//如果是cancelled状态,那就将其向前遍历找到正常的等待状态,依靠外层的自旋重新判断是否阻塞
//省下的节点状态都通过CAS设置成signal状态重新进入判断
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
// 获取前驱结点的状态值
int ws = pred.waitStatus;
// 若前驱结点的状态为SIGNAL状态的话,那么该结点就不要想事了,直接返回true准备休息
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.
*/
// 若前驱结点的状态为CANCELLED状态的话,那么就一直向前遍历,直到找到一个不为CANCELLED状态的结点
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.
*/
// 剩下的结点状态,则设置其为SIGNAL状态,然后返回false标志等外层循环再次判断
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
//这里其实就是一个阻塞等待,之后检查是否被中断过
//这里唤醒有两种,一种是unpark一种是interrupt
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
//之后是对于解锁的源码解析
public void unlock() {
sync.release(1);
}
//这里其实就是解锁方法
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
//获取锁的资源值,并且做-1操作
int c = getState() - releases;
//这里查看当前线程是不是独占线程
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//这里判断锁的资源值是不是为0了,为0了就将独占锁的位置设置为null
//不为0 代表还有可重入锁,需要继续解锁
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
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;
//如果小于0那就将其置为0
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;
//如果为null,或者状态是CANCELLED那就从尾节点遍历找到
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);
}
在这里非公平锁和公平锁的区别主要在两个位置
首先就是在调用lock方法时候,非公平锁会首先调用CAS操作做获取锁的尝试,而公平锁则不会
另外就是在尝试加锁的时候,非公平锁会直接尝试获取锁,而公平锁会首先判断队列中有没有等待的,有的话不抢