您的位置:首页 > 产品设计 > UI/UE

从ReentrantLock去分析AbstractQueuedSynchronizer

2017-03-04 18:06 771 查看
在并发中,锁是一个重要的工具,能帮助程序处理好数据并发处理不一致的问题,而AbstractQueuedSynchronizer在其中扮演中重要的角色。在设计所锁的时候,应该思考怎么锁能解决什么问题,而这个问题本质是由于什么原因引起。并发问题说到底是由于资源共享竞争使用引起的。锁就是为了防止资源不合理竞争使用导致的并发问题。

AQS简介

AbstractQueuedSynchronizer简称AQS,是Java并发包Concurrent中比较重要的类。顾名思义,它是个抽象的类,是一个和同步相关的队列。这里的同步当然是锁的意思。ReentrantLock和Semaphore都继承扩展了它。了解一个东西,最开始需要思考这个东西设计思想是什么?如果是你,会怎么样设计?这里以ReentrantLock为例,试着分析其中的原理。

AQS可以理解为一个资源的协作管理器。这里的资源指的是一个int值state,每个线程都想获取或者操作这个值。state初始值为0,用volatile修饰。保证可见性,是其他线程能立刻看到这个变量的修改。

/**
* The synchronization state.
*/
private volatile int state;//初始值为0


AQS包含有头节点和尾节点,头节点是个哑节点.

private transient volatile Node head;

/**
* Tail of the wait queue, lazily initialized.  Modified only via
* method enq to add new wait node.
*/
private transient volatile Node tail;


AQS继承了AbstractQueuedSynchronizer,可以设置保存独占锁的线程。

public abstract class AbstractQueuedSynchronizer
extends AbstractOwnableSynchronizer
implements java.io.Serializable


AQS的队列是个FIFO的双向链表,节点保存的数据是并发的线程。

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;

volatile int waitStatus;

volatile Node prev;

volatile Node next;

volatile Thread thread;

Node nextWaiter;
...
}


怎么获取锁

我们来来看非公平锁,这也是ReentrantLock默认方式

public ReentrantLock() {
sync = new NonfairSync();
}


获取锁时只有两种情况:一种情况是state没有被占有,然后通过CAS方式设置该state并占有锁;另外一种是锁被其他线程占有,然后尝试获取资源state

final void lock() {
if (compareAndSetState(0, 1))//占有锁成功
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);//尝试获取
}


分析一下acquire,主要是尝试获取资源state,若没有成功,加入到等待队列中,进入阻塞状态

public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}


tryAcquire最后会调用nonfairTryAcquire方法,这个方法前半部分和前面首次获取锁的方法类似,尝试再次获取state并占有它,成功返回true;失败后判断当前线程是否已经是占有state的线程,如果是的,state加1,表示锁可以重入;否则返回false.

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;
}


接着上面返回false情况说,这时获取锁是失败的,就需要另外一种策略来等待锁的释放后再获取锁。这种策略就是将等待的线程加入到一个队列中.

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;
}
}
enq(node);
return node;
}


从上面代码不难看出,先尝试尾插快速插入,尝试不成功后说明尾节点为null,初始化尾节点继续插入。分析完了插入,还需要考虑一个问题是让线程停下来,等待恰当时机再获取资源。acquireQueued方法就是做这个事情。先建一个死循环,第一步是判断当前节点的前驱节点是否是头节点,如果是尝试获取该资源state,否则让线程停下来等待

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);
}
}


来看看怎么判断线程该停下来。若前驱节点pred的waitStatus为Node.SIGNAL,返回true,表示需要停下来;如果waitStatus小于0,说明线程已经被取消,不能阻塞停下来,不断从后向前遍历找到waitStatus为非正的前驱节点;如果waitStatus等于0,初始为Node.SIGNAL.

private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL)
/*
* This node has already set status asking a release
* to signal it, so it can safely park.
*/
return true;
if (ws > 0) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
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.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}


线程停下来代码很简单,直接调用本地的JNI方法,等待upPark。

private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}


怎么释放锁?

释放锁入口

public void unlock() {
sync.release(1);
}


调用了AQS的release方法

public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}


先尝试释放占有的资源,这里比较简单,将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;
}


唤醒等待的线程。正常情况下Node的后继节点就是要唤醒的线程,但是当取消或者null时,需要从后往前找,直到最前面一个没有被取消的Node,找到后唤醒它。为什么要找到最前面的Node,而不是找到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);
}


思考

为什么总是唤醒最前面的节点(即头节点的后继节点)?

AQS的队列是个FIFO的队列,这样做的目的是为了防止线程饿死。试想如果总是选取最后的节点唤醒,最前面的节点就没有机会唤醒了。

公平锁和非公平锁的区别?

上面讲到了非公平锁的实现,这也是默认的最有效率的实现方式。公平锁获取只是多了一行代码, hasQueuedPredecessors判断是否有前驱节点,如果有的话继续找到最前面的节点,即只有最前面的节点才有资格获取锁。也就是说新加进来节点中的线程不能马上获取锁,而必须让先进入队列节点中的线程获取锁。这虽然保证了公平性,但是却牺牲了性能。

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并发
相关文章推荐