AQS
可重入锁
已成功获取锁的线程再次获得该锁时可以为count++,只要count>0表示锁被该线程持有,每次释放锁count–直到count=0表示该线程不再持有锁;可重入锁可以有效避免单一线程自己出现死锁。
LockSupport
LockSupport是用来创建锁和其他同步类的基本线程阻塞原语;
其中的park()和unpark()方法用来阻塞线程和解除阻塞。
synchronized中的wait()实现线程等待,notify()实现线程唤醒;必须先等待再唤醒;
lock中condition的await()实现线程等待,signal()实现线程唤醒;必须先等待再唤醒;
LockSupport中的park()、unpark()是他们的升级版,功能更强。
每一个线程会拥有一个permit(0/1),如果LockSupport.park()则permit为0,则表示当前线程被阻塞;如果LockSupport.unpark(),permit为1,则表示当前线程被唤醒;多次调用park()permit也只能为0,多次调用unpark()permit也只能为1;LockSupport的好处在于他不需要syn同步代码块,也不需要lock加锁解锁,直接使用这两个函数即可。
AbstractQueuedSynchronizer抽象队列同步器
以上两个都是AQS的前置知识,现在从源码分析AQS。
AQS是实现各种同步锁的基础框架以及整个JUC体系的基石。
内部结构:int state表示占用资源者数量+CLH双向队列(暂时获取不到锁的线程会进入队列等待)
state使用volatile修饰来表示同步状态,通过内置的FIFO队列来完成资源获取的排队工作,将每条要去抢占资源的线程封装成一个Node节点实现锁分配,通过CAS完成对state值的修改。
static final class Node {
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;
Node nextWaiter;
final boolean isShared() {
return nextWaiter == SHARED;
}
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() { // Used to establish initial head or SHARED marker
}
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
所有的锁实际上就是在重写AQS中的tryAcquire(),tryRelease()等方法(模板模式)
以ReentrantLock为例理解AQS
AQS作为一个模板内部的代码分析内部代码没啥意义,所以直接挑一个他的实现类:
ReentrantLock内部有一个成员变量sync,继承了AQS,默认构造为非公平锁。
公平锁与非公平锁
hasQueuedPredecessors()是公平锁加锁时判断等待队列中是否存在有效节点的方法。
以ABC三个线程为顺序争抢锁为例,A线程进入时锁无人使用,state为0,则cas(0,1)成功,直接将排他锁的线程改为自己,然后开始进行业务逻辑。
此时B线程来了,首先进行CAS(0,1),一直失败,那么就进入acquire()方法中:
先调用了tryAcquire()方法,
内部函数为nonfairTryAcuquire()
此时再次判断state状态(万一刚才没抢到现在有机会了呢),能CAS抢到就成为互斥锁的线程,否则先去判断是不是可重入锁,是的话也能占有锁;否则就算取锁失败了;
取锁失败后进入addWaiter(Node.EXCLUSIVE)方法中
这时候会获取CLH中的尾部节点,如果尾部节点为空,会使用enq()方法,进行队列初始化操作,生成虚拟头节点(也叫哑节点,哨兵节点),虚拟节点的waitStatus=0表示初始值,Thread=null表示是虚拟节点无线程关联,并将该线程B生成一个waitStatus=0的节点置于队尾。
此时Acquire()中if()的前两个条件!tryAcquire&&addWaiter()都做过了,这回B放弃了,只能进入队列等待,也就是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);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
如果pre是头节点表示已经在队头了,此时再次尝试获取锁:
如果tryAcquire()成功了,那么就用setHead()把虚拟头节点释放,把自己设置成头节点并且把thread改为null,并将指针修改;然后把虚拟头节点的指针都指NULL,方便GC回收;
否则进入等待,核心就是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 {
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
进入该函数后会先看本节点的前一个节点的状态,如果是SIGNAL状态,表示等资源释放时前一个节点会通知自己,返回true;如果>1说明这个pre节点的状态为CANCEL,他被取消了,那么前一个节点就被淘汰了;再不然就把前一个节点设置为SIGNAL状态。
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
然后使用LockSupport()方法,把自己阻塞在这里(别再浪费CPU抢了,赶紧把自己阻塞了等着吧);等什么时候被unpark()了,就会继续往下走;
一会儿之后C也来了,他也经过tryAcquire()方法,啥也没抢到,只能调用addWaiter(),此时CLH队列已经被初始化了,那么他就直接使用cas去把自己入队;经过上述一系列操作之后C也被阻塞在这里了;
到这里加锁、入队的过程就结束了,那么释放锁就比较简单了:
Unlock()调用
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) {
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
对state进行cas,如果为0了返回一个true标识符;
如果头节点是虚拟节点并且状态不是初始值表示后面有人等着,对他进行unpark()解除阻塞
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 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);
}
unparkSuccessor()把node的状态改为0并且释放虚拟节点,把node变为头节点。