目录
AQS概念
抽象队列同步器,是除了java自带的synchronized关键字之外的锁机制。AQS就是基于虚拟的双向队列(双向链表),用volatile修饰共享int变量state,线程通过CAS+自旋去改变状态符,成功则获取锁成功,失败则进入等待队列,等待被唤醒。关键词:双向链表、CAS、自旋。AQS 定义了两种资源共享方式:
- Exclusive:独占,只有一个线程能执行,如ReentrantLock(只有修改state成功的一个线程获得锁,state由0变1)
- Share:共享,多个线程可以同时执行,如Semaphore、CountDownLatch、ReadWriteLock,CyclicBarrier (大家都能修改state,state由0变N)
AQS底层使用了模板方法模式
- 使用者继承AbstractQueuedSynchronizer并重写指定的方法。(这些重写方法很简单,无非是对于共享资源state的获取和释放)
- 将AQS组合在自定义同步组件的实现中,并调用其模板方法,而这些模板方法会调用使用者重写的方法。这和我们以往通过实现接口的方式有很大区别,这是模板方法模式很经典的一个运用。
核心方法:
- tryAcquire(int):独占方式。尝试获取资源,成功则返回true,失败则返回false。
- tryRelease(int):独占方式。尝试释放资源,成功则返回true,失败则返回false。
- tryAcquireShared(int):共享方式。尝试获取资源。负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。
- tryReleaseShared(int):共享方式。尝试释放资源,如果释放后允许唤醒后续等待结点返回true,否则返回false。
CountDownLatch源码
CountDownLatch主要实现了tryReleaseShared方法和tryAcquireShared方法。主任务A分N个子线程去执行,state就初始化为N,N个线程并行执行,每个线程执行完之后countDown()一次,state就会CAS减一。当state不为0时,主线程A执行到await()时会挂起线程,当N子线程全部执行完毕,state=0,会唤醒主调用线程,主调用线程就会从await()函数返回,继续之后的动作。
- CountDownLatch的await方法:
//调用AQS提供的acquireSharedInterruptibly方法
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//AQS提供的acquireSharedInterruptibly方法
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
//当state不为0时,进入AQS提供的doAcquireSharedInterruptibly方法
doAcquireSharedInterruptibly(arg);
}
//CountDownLatch实现的tryAcquireShared方法,state的初始值在new CountDownLatch(int count)时设置的,然后线程调用countDown方法会减1
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
//AQS提供的doAcquireSharedInterruptibly方法,将当前线程(不是执行countDown的那些线程,而是调度那些线程的主线程)的节点添加到队列,然后挂起线程。当state为0时会唤醒线程,然后进入自旋代码块中唯一退出的入口,线程得以继续执行
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.SHARED);//入队列
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
//当state为0时,r为1,进入以下代码
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
//挂起线程
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
- CountDownLatch的countDown方法:
//调用AQS的releaseShared方法
public void countDown() {
sync.releaseShared(1);
}
//AQS的releaseShared方法
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
//当state为0时,也就是说线程都执行完,进入doReleaseShared方法
doReleaseShared();
return true;
}
return false;
}
//CountDownLatch实现的tryReleaseShared方法,通过自旋+cas将state减1
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (;;) {
int c = getState();
if (c == 0)
return false;
int nextc = c-1;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
//AQS提供的doReleaseShared方法,unparkSuccessor方法可以唤醒线程
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h); //唤醒线程
}
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
ReenTrantLock源码
ReentrantLock(可重入独占式锁),state初始化为0,表示未锁定状态,A线程lock()时,会使用CAS将state加1,占用失败的其他线程去tryAcquire,失败后入队列并且挂起线程;当A线程unlock()即执行ReenTrantLock的tryRelease方法,释放占有的锁,将state减1,当state为0时返回true,唤醒队列中的线程其他线程才有机会获取该锁。A释放锁之前,自己也是可以重复获取此锁(state累加),这就是可重入的概念。获取多少次锁就要释放多少次锁,保证state是能回到零态的。
以非公平锁为例,
- 调用ReenTrantLock的lock方法
//调用ReenTrantLock的lock方法,若state为0使用cas将state设置为1,表示占用锁
//若占用失败调用AQS的acquire方法
final void lock() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
//AQS的acquire方法,调用ReenTrantLock的tryAcquire方法判断是否加锁失败,或者不是锁重入,则执行入队列操作,并调用AQS的acquireQueued方法挂起线程
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
//ReenTrantLock的tryAcquire,判断是否加锁失败,或者不是锁重入
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
//ReenTrantLock的nonfairTryAcquire方法
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
//AQS的acquireQueued方法挂起线程(parkAndCheckInterrupt方法挂起线程)
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;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
-
调用ReenTrantLock的unlock方法
//调用ReenTrantLock的unlock方法,执行AQS提供的release方法
public void unlock() {
sync.release(1);
}
//AQS提供的release方法,执行ReenTrantLock的tryRelease方法,释放占有的锁,将state减1,当state为0时返回true,唤醒队列中的线程
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
//执行ReenTrantLock的tryRelease方法,释放占有的锁,将state减1,当state为0时返回true
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
非公平锁是因为,每个线程首先尝试获取锁,获取不到时才入队列,所以当一个持有锁的线程释放锁时,有可能恰好新来了一个请求锁的线程,排在队列前抢占了锁,所以是非公平的。而公平锁的lock方法对比非公平锁, 没有了if else 也就意味着新来的线程没有插队的机会, acquire方法也会像非公平锁一样首先调用tryAcquire插队试试,但是只有队列为空或着本身就是head,那么才可能成功,如果队列非空那么扔到队列尾部。
ReadWriteLock读写锁也是使用AQS,ReentrantReadWriteLock是他的实现,支持读锁共享,原理是使用AQS进行同步,修改state时用高16位和低16位来区分读写锁,加锁时需要考虑读写锁互斥、读写锁最大数量、重入等。