AQS
一、AQS(AbstractQueuedSynchronizer)抽象队列同步框架:java中实现锁机制的形式有两种,一种是通过syschronized关键字来实现,另外一种既是通过抽象线程同步框架来实现。syschronized通过修改字节码加入监视器类来实现最终会调用cpu的锁来实现。而AQS是通过双向队列+volatile关键字来实现,相对syschronized其免去了字节码层面的修改,不用调用cpu的锁来实现,加锁释放锁更加的快捷,避免调用cpu锁导致的资源浪费。
二、原理
1.属性
//共享锁标志
static final Node SHARED = new Node();
//独占锁标志
static final Node EXCLUSIVE = null;
//待销毁状态
static final int CANCELLED = 1;
//后续线程可获取锁
static final int SIGNAL = -1;
//等待条件
static final int CONDITION = -2;
//传播属性,共享线程使用
static final int PROPAGATE = -3;
//等待状态
volatile int waitStatus;
//上个节点
volatile Node prev;
//下个节点
volatile Node next;
//所属线程
volatile Thread thread;
//队列尾部
private transient volatile Node tail;
//锁状态
private volatile int state;
2.构造方法,AQS提供三种不同的构造方法,对应头部所插入(共享节点标志)、插入阻塞队列、插入等待队列。
//无参构造方法,添加虚拟头节点,创建共享锁标志使用
Node() {
}
//添加等待队列使用
Node(Thread thread, Node mode) {
this.nextWaiter = mode;
this.thread = thread;
}
//添加阻塞队列使用
Node(Thread thread, int waitStatus) {
this.waitStatus = waitStatus;
this.thread = thread;
}
3.入队,队列为FIFO(先入先出的双向队列)在尾部进行插入,插入通过CAS修改队尾元素来判定是否插入成功,因为插入对应创建新线程属于并发操作,存在插入失败的情况。CAS操作失败会调用enq方法进行自旋,直至将元素插入队列。
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
Node pred = tail;
//判断尾节点是否为空,不为空直接插入
if (pred != null) {
node.prev = pred;
//将插入节点设置为尾节点,CAS操作成功可以判定已成功插入队列
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//头部节点为空,或者插入失败进入该方法
enq(node);
return node;
}
enq插入,这里为自旋操作保证将元素插入到队列中,同时如果没有会设置头部节点。
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) {
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
4.获取锁,acquire方法在我们线程进行加锁时(这里针对ReentrantLock)调用。该方法首先是尝试获取锁,如果成功会进行真正的获取锁操作acquireQueued,获取锁会先将当前节点插入队列尾部,取第一个可获取锁元素取消阻塞状态。这里tryAcquire方法会在各个实现类中进行实现,不同形式的锁有不同的实现。
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
tryAcquire仅仅是一个抽象方法,具体实现在具体的实现类中
protected boolean tryAcquire(int arg) {
throw new UnsupportedOperationException();
}
acquireQueued获取锁,这里是真正的获取锁操作。如果获取失败则会对队列进行处理并且会将线程进行阻塞。
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);
//释放当前节点的下级引用,帮助GC
p.next = null;
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
predecessor获取前置线程,如果没有则抛出异常。
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
shouldParkAfterFailedAcquire判断是否需要对阻塞队列进行阻塞操作。
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
//可安全的阻塞
return true;
if (ws > 0) {
//表示线程已经取消,直接将其移除队列
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
//将前置节点状态置为-1,这里保证了前置节点为-1保证了后续的操作正确执行
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
parkAndCheckInterrupt将线程阻塞掉,返回线程中断状态。
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
cancelAcquire,获取锁成功后的处理。
private void cancelAcquire(Node node) {
// 如果节点为空,直接返回。
if (node == null)
return;
//将节点的线程置为空
node.thread = null;
// Skip cancelled predecessors
Node pred = node.prev;
while (pred.waitStatus > 0)
//获取状态小于等于0的节点
node.prev = pred = pred.prev;
Node predNext = pred.next;
//将当前线节点状态程置为可销毁
node.waitStatus = Node.CANCELLED;
//如果节点为尾部节点,则将前置状态小于等于0的节点设置为尾部节点
if (node == tail && compareAndSetTail(node, pred)) {
//设置下级节点
compareAndSetNext(pred, predNext, null);
} else {
int ws;
//如果前置节点不为空、线程不为空,且能置为阻塞状态能置为-1
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);
}
// help GC
node.next = node;
}
}
将头节点置空
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
5.释放锁
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
//将最前一个可获取锁的节点阻塞状态取消
unparkSuccessor(h);
return true;
}
return false;
}
unparkSuccessor取消阻塞状态
private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
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);
}
三、队列的使用
AQS中维护了两个队列,阻塞队列和等待队列。阻塞队列用来保存线程资源,等待队列用来实现线程的同步,主要是实现await和singnal相关的方法。其中阻塞队列使用的是双向队列,是因为我们的我们的线程竞争原则是先入先出,加入是在尾部,线程获取锁实在头部。由于竞争关系,最后入队列的元素可能存在问题。为了保证正确性,遍历时从后向前进行搜索,tail元素修改成功保证入库成功,这样就能功保证数据查找的正确性。等待队列使用单项链表,因为同一队列的入队和出队正常情况下是互斥的,不存在竞争关系。
三、运用
AQS的实现的锁多种多样,有ReentrantLock、Semaphore、CountDownLatch、CyclicBarrier。