AQS
AQS个人理解就是一个有优先级的获取锁的线程队列,用cas高效获取锁,同时通过等待线程的挂起大幅减少cas带来的cpu消耗
一般有这几个状态:
整型state :重入计数1表示锁被获取了, 大于0表示重入了多次,等于0表示锁空闲
exclusiveOwnerThread :表示持有锁的线程
Node类型head :表示等待队列头节点
Noe类型 tail :表示等待队列尾结点
Node类的状态量:
//表示共享模式的常量
static final Node SHARED = new Node();
//表示独占模式的常量
static final Node EXCLUSIVE = null;
//表示当前节点的线程被取消
static final int CANCELLED = 1;
//表示释放锁时需要唤醒下一个非CALCELLED节点
static final int SIGNAL = -1;
//通过Condition.signal()进行唤醒,此状态用于ConditionObject(本身就是个队列有firstWaiter,和lastWaiter,通过signal会唤醒头节点,所以我们经常new很多个Condition(多个队列,用的话大部分都是容量为1,保证精确唤醒),先await把当前线程入队,然后调用signal方法进行精确唤醒)
static final int CONDITION = -2;
//表示节点waiterStatus 为共享模式
static final int PROPAGATE = -3;
//----------------以上皆为常量 下面的为Node的状态量---------
//等待状态 表示该节点代表的线程的等待状态如CANCELLED,SIGNAL,PROPAGATE
volatile int waitStatus;
//前一个等待线程的节点(链表左指针)
volatile Node prev;
//后一个等待线程的节点(链表右指针)
volatile Node next;
//节点代表的线程
volatile Thread thread;
//下一个等待的线程,ConditionObject中使用,只需要一个next指针就够了
Node nextWaiter;
通过node类可知,有prev和next两个指针用于ReentrantLock中Syn队列所以为双向列表。
而ConidtionObject只用了nextWaiter则为单链表
ReentrantLock独占模式解析
以下只分析了独占模式的lock。
//默认实现非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}
基类:为公平锁和非公平锁提供基本方法
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = -5179523762034025860L;
/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract void lock();
/**
* Performs non-fair tryLock. tryAcquire is implemented in
* subclasses, but both need nonfair try for trylock method.
*/
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
//获取state
int c = getState();
//为0表示锁未被占用
if (c == 0) {
//cas
if (compareAndSetState(0, acquires)) {
//成功设置持有锁线程为当前线程
setExclusiveOwnerThread(current);
return true;
}
}
//state不为0 查看持有锁线程是否当前线程,是进行重入
else if (current == getExclusiveOwnerThread()) {
//state计数增加
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
//尝试释放锁 releases为释放次数
protected final boolean tryRelease(int releases) {
//重入计数器减少
int c = getState() - releases;
//如果当前线程未持有锁 表示为异常
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//如果减少重入计数后 state为0 则可以完全释放锁,设置持有线程为空
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
final ConditionObject newCondition() {
return new ConditionObject();
}
// Methods relayed from outer class
final Thread getOwner() {
return getState() == 0 ? null : getExclusiveOwnerThread();
}
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
final boolean isLocked() {
return getState() != 0;
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
setState(0); // reset to unlocked state
}
}
非公平锁实现
/**
* Sync object for non-fair locks
*/
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
/**
* Performs lock. Try immediate barge, backing up to normal
* acquire on failure.
*/
final void lock() {
//先cas一波 如果运气好能抢到锁 就不需要进入同步队列速度快
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
//cas失败 调用AbstractQueuedSyncronizerd的acquire方法
acquire(1);
}
//调用父类的尝试获取锁方法
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
AbstractQueuedSyncronizerd
注意上面的acquire方法 aqs入口
先介绍以下Node节点的waitStatus:
public final void acquire(int arg) {
//调用tryAcquire方法即调用子类的tryAcquire方法,如果获取锁成功方法执行完毕。失败:为同步等待队列添加等待节点,并尝试cas(看node是否为第二个节点),如果cas失败则线程进入挂起状态
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
//AbstractQueuedSyncronizerd不支持此方法的实现,强制面向继承使用,具体的实现看 NonfairSync和FairSync的实现
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
//省略、、、、、、、、、、、、
/**
* 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();
//如果是头节点(即node为第二个节点)并且获取锁成功
if (p == head && tryAcquire(arg)) {
//把当前节点置为头节点(aqs的头节点为空节点)
setHead(node);
//原head与node断开连接 原head节点强引用消失 方便GC
p.next = null; // help GC
failed = false;
return interrupted;
}
//如果不是头节点,或者获取锁失败 看是否应该挂起线程
if (shouldParkAfterFailedAcquire(p, node) &&
//挂起线程 此时进入阻塞状态减少自旋消耗(如果线程中断则立即返回true表示线程被中断)
parkAndCheckInterrupt())
interrupted = true;
}
//此时被唤醒则进入下一个循环 尝试获取锁
} finally {
//出现异常 一般为中断一次,那就是线程死了不需要获取锁了,把节点置为cancel状态
if (failed)
cancelAcquire(node);
}
}
//省略、、、、、、、、、、、、
/**
* 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
*/
//是否可以挂起线程(找到一个前面的不为CANCEL状态的节点并设置为signal状态)
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
//获取前一个节点等待状态
int ws = pred.waitStatus;
//如果为SIGNAL状态返回true(SIGNAL表示节点释放锁后会通知下一个节点)
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
//只有CANCAL状态大于0
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
//向前查找节点并设值node的pre指针
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
//找到不为CALCELLED状态的节点pre的next节点
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.
*/
//小于等于0 则前一个节点只有 0和PROPAGATE状态(Condition状态用于ConditionObject类中肯定不是),那我需要把前一个节点更新为SIGNAL状态,然后调用的方法里会自旋一次确保在挂起前获取不到锁(因为有PROPAGATE共享状态有可能会获得锁),再进入挂起状态
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
//只要不是signal都返回false
return false;
}
/**
* 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;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//失败进入此方法(node的pre指针已经设置值 此方法只关注tail的next的值)
enq(node);
return node;
}
/**
* Inserts node into queue, initializing if necessary. See picture above.
* @param node the node to insert
* @return node's predecessor
*/
private Node enq(final Node node) {
//自旋 保证100%入队
for (;;) {
Node t = tail;
//tail为null说明还未初始化
if (t == null) { // Must initialize
//先初始化头节点
if (compareAndSetHead(new Node()))
tail = head;
} else {
//设置尾节点
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
lock相关分析基本上完成
借用了一个图片 出处:https://www.cnblogs.com/waterystone/p/4920797.html
释放锁:
/**
* 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}
*/
//此时肯定是头结点获得了锁,线程不阻塞了,运行的unlock()代码
public final boolean release(int arg) {
//尝试释放锁(重入次数为1就返回true,重入次数为多次,那需要多释放几次才会为true)
if (tryRelease(arg)) {
Node h = head;
//有头结点而且被初始化过
if (h != null && h.waitStatus != 0)
//唤醒最接近头结点的一个非CALCELLED结点
unparkSuccessor(h);
return true;
}
return false;
}
/**
* Wakes up node's successor, if one exists.
*
* @param node the 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)
//清除状态
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的下一个节点
Node s = node.next;
//如果下一个节点为CALCELLED状态
if (s == null || s.waitStatus > 0) {
s = null;
//从尾节点开始向前搜索一个最接近node的线程正常运行的节点
for (Node t = tail; t != null && t != node; t = t.prev)
if (t.waitStatus <= 0)
s = t;
}
if (s != null)
//唤醒线程
LockSupport.unpark(s.thread);
}