1.首先看下aqs的继承关系,可以帮助我们更好的了解源码
public abstract class AbstractQueuedSynchronizerextends AbstractOwnableSynchronizerimplements java.io.Serializable
接口“Serializable”不用多说了吧,序列化作用。那么我们重点讲讲“abstractOwnableSynchronizer”中有啥方法。
1.1.abstractOwnableSynchronizer
/*** The current owner of exclusive mode synchronization.*/private transient Thread exclusiveOwnerThread;/*** Sets the thread that currently owns exclusive access.* A {@code null} argument indicates that no thread owns access.* This method does not otherwise impose any synchronization or* {@code volatile} field accesses.* @param thread the owner thread*/protected final void setExclusiveOwnerThread(Thread thread) {exclusiveOwnerThread = thread;}/*** Returns the thread last set by {@code setExclusiveOwnerThread},* or {@code null} if never set. This method does not otherwise* impose any synchronization or {@code volatile} field accesses.* @return the owner thread*/protected final Thread getExclusiveOwnerThread() {return exclusiveOwnerThread;}
其实注释上已经讲得很清楚了,定义了一个属性,是一个线程,该线程是:在独占模式下同步锁的拥有者,并有两个和他有关的方法,get,set。
看到这里提到一个名字:独占模式,难不成还有别的模式,那么别的模式叫什么,有哪些实例?这个问题我会在下一篇文章讲到。
2.源码分析
2.1.内部静态类:node
static final class Node {/** Marker to indicate a node is waiting in shared mode */static final Node SHARED = new Node();/** Marker to indicate a node is waiting in exclusive mode */static final Node EXCLUSIVE = null;/** waitStatus value to indicate thread has cancelled */static final int CANCELLED = 1;/** waitStatus value to indicate successor's thread needs unparking */static final int SIGNAL = -1;/** waitStatus value to indicate thread is waiting on condition */static final int CONDITION = -2;/*** waitStatus value to indicate the next acquireShared should* unconditionally propagate*/static final int PROPAGATE = -3;/*** Status field, taking on only the values:* SIGNAL: The successor of this node is (or will soon be)* blocked (via park), so the current node must* unpark its successor when it releases or* cancels. To avoid races, acquire methods must* first indicate they need a signal,* then retry the atomic acquire, and then,* on failure, block.* CANCELLED: This node is cancelled due to timeout or interrupt.* Nodes never leave this state. In particular,* a thread with cancelled node never again blocks.* CONDITION: This node is currently on a condition queue.* It will not be used as a sync queue node* until transferred, at which time the status* will be set to 0. (Use of this value here has* nothing to do with the other uses of the* field, but simplifies mechanics.)* PROPAGATE: A releaseShared should be propagated to other* nodes. This is set (for head node only) in* doReleaseShared to ensure propagation* continues, even if other operations have* since intervened.* 0: None of the above** The values are arranged numerically to simplify use.* Non-negative values mean that a node doesn't need to* signal. So, most code doesn't need to check for particular* values, just for sign.** The field is initialized to 0 for normal sync nodes, and* CONDITION for condition nodes. It is modified using CAS* (or when possible, unconditional volatile writes).*/volatile int waitStatus;/*** Link to predecessor node that current node/thread relies on* for checking waitStatus. Assigned during enqueuing, and nulled* out (for sake of GC) only upon dequeuing. Also, upon* cancellation of a predecessor, we short-circuit while* finding a non-cancelled one, which will always exist* because the head node is never cancelled: A node becomes* head only as a result of successful acquire. A* cancelled thread never succeeds in acquiring, and a thread only* cancels itself, not any other node.*/volatile Node prev;/*** Link to the successor node that the current node/thread* unparks upon release. Assigned during enqueuing, adjusted* when bypassing cancelled predecessors, and nulled out (for* sake of GC) when dequeued. The enq operation does not* assign next field of a predecessor until after attachment,* so seeing a null next field does not necessarily mean that* node is at end of queue. However, if a next field appears* to be null, we can scan prev's from the tail to* double-check. The next field of cancelled nodes is set to* point to the node itself instead of null, to make life* easier for isOnSyncQueue.*/volatile Node next;/*** The thread that enqueued this node. Initialized on* construction and nulled out after use.*/volatile Thread thread;/*** Link to next node waiting on condition, or the special* value SHARED. Because condition queues are accessed only* when holding in exclusive mode, we just need a simple* linked queue to hold nodes while they are waiting on* conditions. They are then transferred to the queue to* re-acquire. And because conditions can only be exclusive,* we save a field by using special value to indicate shared* mode.*/Node nextWaiter;/*** Returns true if node is waiting in shared mode.*/final boolean isShared() {return nextWaiter == SHARED;}/*** Returns previous node, or throws NullPointerException if null.* Use when predecessor cannot be null. The null check could* be elided, but is present to help the VM.** @return the predecessor of this node*/final Node predecessor() throws NullPointerException {Node p = prev;if (p == null)throw new NullPointerException();elsereturn p;}Node() { // Used to establish initial head or SHARED marker}Node(Thread thread, Node mode) { // Used by addWaiterthis.nextWaiter = mode;this.thread = thread;}Node(Thread thread, int waitStatus) { // Used by Conditionthis.waitStatus = waitStatus;this.thread = thread;}}
我原封不动的把源码给copy下来了,包括注解。现在就分析下AQS核心这个内部静态类,干了什么?
从注解中我们发现,其有两种模式:共享模式、独占模式。
并且其中也有两个链表,链表中有“next”和“pre”属性,毫无疑问是一个双向链表:一个共享模式的链表、一个独占模式的链表。
所以看源码其实就三个东西:一个叫数据结构、一个叫算法、一个叫设计模式,加上网络基础知识,计算机基础知识,一般的源码肯定水到渠成的。
我们先看一个属性:waitStatus。等待状态,而且还被volatile修饰了,再看下它有几种状态:
·SIGNAL=-1:一个需要成功线程唤醒的状态 注:大家可以了解下park与wait、unpark与notify的用法的区别?可能对大家再并发线程或者一些特殊情况处理会有帮助。
·CANCELLED=1:当前线程已经被取消了,不难理解
·CONDITION=-2:表明当前线程还处于等待队列中
·PROPAGATE=-3:下一次的请求无条件传播
·0:以上都不是
next:表示下一个节点,prev:表示上一个节点,thread:表示该节点的线程,nextWaiter:只有共享模式下,这个值才会有值,是一种特殊的值,只会在共享模式下。所以是否是共享模式,就是通过该值确定的
在AQS中有头结点与尾结点,state:表示一个同步的状态,当前有没有现成获得锁就是通过它进行判断的。所以在aqs中除了用到了volatile,还用到了CAS,两者保证了其是线程安全的。
2.2.内部类:ConditionObject
2.2.1.继承关系:condition,主要两个方法:一个await与signal,是不是感觉和object中的方法wait与notify很相似。
2.2.2.内部解析
其实这个类就是AQS当中的等待队列,队列当中有两个节点,一个是头结点,一个尾结点。
3.独占锁之ReentrantLock
3.1.继承关系:lock
lock:堵塞获得锁
lockInterruptibly:堵塞获得锁,除非当前线程被中断
tryLock:尝试获得锁,成功返回true,失败返回fasle
unlock:释放锁
codition:创建一个等待队列
3.2.解读源码
3.2.1.抽象类Sync,继承了aqs,所以该类属于其基类,所以在他基础上,实现了公平锁与非公平锁
lock:抽象方法,子类实现
/**
* Performs {@link Lock#lock}. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract void lock();
nonfairTryAccuire:该方法中有一个int型的参数,所以表明该锁是可以重入的。
/**
* 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();
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;
}
先拿到当前线程,在获得是否有线程获得了该锁,如果没有线程获得该锁,则cas其state值,如果cas成功,说明当前线程获得锁成功,则将当前线程赋值给独占模式下所拥有的的线程,并返回true;
如果有线程获得了锁,则判断获得锁的线程是否就是当前线程,如果是,则state加上重入次数,返回true,否则fasle
tryRelease:尝试释放锁,参数也有个int参数,表示尝试释放重入的次数。
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;
}
这个代码没啥可以解释的吧,应该都能看得懂
isHeldExclusively:主要就是判断当前线程是否拿到了独占锁
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();
}
newCondition:创建一个等待队列
final ConditionObject newCondition() {
return new ConditionObject();
}
getOwner:获取拥有锁的线程
final ConditionObject newCondition() {
return new ConditionObject();
}
getHoldCount:获取当前线程获取锁的次数
final int getHoldCount() {
return isHeldExclusively() ? getState() : 0;
}
isLocked:是否有线程获取了锁
final boolean isLocked() {
return getState() != 0;
}
readObject:从流中获取一个实例,并将锁的状态设置为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
}
3.2.2.NonFairSync—非公平锁
/**
* 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() {
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
其实代码很简单,实现抽象类的lock:cas设置state锁的状态,如果成功,则将当前线程赋值给拥有锁线程属性;如果失败,则调用aqs的acquire(1)方法
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
很简单,就是先尝试获取,如果失败,则将其加到等待队列中,并且等待唤醒争抢锁,除非线程中断,有兴趣的同学可以看看里面的代码,怎么进行争抢的。里面其实就是一个死循环,跳出循环只有两种可能,一种是成功,一种是线程中断,如果线程中断则取消请求
tryAcquire:其实调用的就是父类的nonfairTryAcquire
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
3.2.3.FairSync—公平锁
/**
* Sync object for fair locks
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
acquire(1);
}
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}
lock:发现了与非公平锁有不一样的地方了吧。为啥是公平的,就是因为他不会一上来就去抢锁,而是先尝试(尝试自己有自己的实现逻辑),不行直接加到队列中去,看出他是公平的地方了吧。
tryAcquire:重点来了,公平锁在这个地方也有体现。首先会先判断是否有线程获得了锁,如果没有线程获得锁,则判断等待队列中是否只有一个线程等待,并且头结点的下一个节点线程是否是当前线程,如果是说明下一个可以争抢的节点就是他,所以直接cas锁的状态state,成功说明增强成功,设置占用线程,返回true;
如果有线程获得了锁,则判断获得锁的线程与当前线程是否一样,一样则增加重入次数。
注:有个地方希望大家注意一点,可能大家不仔细看的话,没有注意到这一点
/**
* 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 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);
}
唤醒线程的时候,一般情况下,是直接唤醒成功获得锁线程节点的下一个节点,但是如果很巧的是,下一个节点被取消或者为null的情况,aqs会从队列底部去唤醒一个线程。
4.共享锁—CountDownLatch
同样,内部也有一个类Sync继承了aqs
/**
* Synchronization control For CountDownLatch.
* Uses AQS state to represent count.
*/
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(int count) {
setState(count);
}
int getCount() {
return getState();
}
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -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;
}
}
}
构造函数中的count,就是CountDownLatch中构造函数的参数。其实原理超级简单,所谓的CountDownLatch中共享模式其实就是把我们获取锁的时候反过来,我们刚开始锁的状态state是0,但是在该类中就必须是一个大于0的值,我们获得锁了,然后state在加,而该类则类似释放一样,在减,减到0了,说明锁释放了。
/**
* Constructs a {@code CountDownLatch} initialized with the given count.
*
* @param count the number of times {@link #countDown} must be invoked
* before threads can pass through {@link #await}
* @throws IllegalArgumentException if {@code count} is negative
*/
public CountDownLatch(int count) {
if (count < 0) throw new IllegalArgumentException("count < 0");
this.sync = new Sync(count);
}
构造函数,很清晰,其实就是new了一个aqs的实现类
看一下方法countDown
/**
* Decrements the count of the latch, releasing all waiting threads if
* the count reaches zero.
*
* <p>If the current count is greater than zero then it is decremented.
* If the new count is zero then all waiting threads are re-enabled for
* thread scheduling purposes.
*
* <p>If the current count equals zero then nothing happens.
*/
public void countDown() {
sync.releaseShared(1);
}
/**
* Returns the current count.
*
* <p>This method is typically used for debugging and testing purposes.
*
* @return the current count
*/
public long getCount() {
return sync.getCount();
}
如果默认不传参数,则默认state-1
下面就是共享模式的代码
/**
* Acquires in shared uninterruptible mode.
* @param arg the acquire argument
*/
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
