Lock特性
lock接口提供synchronized关键字不具备的主要特性
特性 | 描述 |
---|---|
尝试非阻塞的获取锁 | 当前线程尝试获取锁,如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁 |
能被中断的获取锁 | 与synchronized不同,获取到锁的线程能响应中断,当获取到锁的线程被中断时,中断异常会被抛出,同时锁会被释放 |
超时获取锁 | 在截止指定的时间内获取锁,截止时间到了仍无法获取锁,则返回 |
ReentrantLock特性
ReentrantLock 实现了标准的互斥操作,也就是一次只能有一个线程持有锁,也即所谓独占锁的概念。实际上独占锁是一种保守的锁策略,在这种情况下任何“读/读”,“写/读”,“写/写”操作都不能同时发生。但是同样需要强调的一个概念是,锁是有一定的开销的,当并发比较大的时候,锁的开销就比较客观了。所以如果可能的话就尽量少用锁,非要用锁的话就尝试看能否改造为读写锁。
类图关系
通过类图,reentrantlock主要实现是通过队列同步器AbstractQueuedSynchronized来实现。
AbstractQueuedSynchronized
队列同步器主要使用过一个FIFO双向队列来完成同步状态(volatile类型的state)的管理,当前线程获取同步状态失败时,同步器会将当前线程以及等待状态信息构造成一个节点(node),并将其加入同步队列,同时会阻塞当前线程,当同步状态释放时(即获得锁的线程 释放锁),会把首节点中的线程唤醒,让其再次尝试获取同步状态。
源码解析
ReentrantLock锁分为公平锁(failsync)和非公平锁(nonfailsync)两种,默认是非公平锁。
nonfailsync代码如下:
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() {
//通过cas操作去更新锁状态,更新成功,则获得锁,否则,acquire操作,尝试获取锁。
if (compareAndSetState(0, 1))
//保存获得独占锁的线程
setExclusiveOwnerThread(Thread.currentThread());
else
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
AbstractQueuedSynchronizer中acquire方法:
public final void acquire(int arg) {
//尝试获取锁(即更新同步状态),失败的话,加入到FIFO队列中去自旋转。
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
下面主要分析tryAcquire(尝试更新同步状态)、acquireQueued(节点加入队列,自旋尝试获取锁)、addWaiter(生成节点)这三个方法。
tryAcquire解析
非公平锁中tryAcquire最终实现是nonfairTryAcquire.
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//state状态值为0,则cas操作更新。
if (c == 0) {
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//state值不为0,说明已经有线程获得锁,判断获得锁的线程是否为当前线程,是,则累加state值,也是锁的可重入机制。
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;
}
addWaiter解析
首先介绍节点的状态
状态 | 描述 |
---|---|
CANCELLED | 值为1,由于在同步队列中等待的线程 等待超时或者被中断,需要从同步队列中取消等待,节点进入改该状态将不会变化 |
SIGNAL | 值为-1, 该节点的后继节点将会被唤醒,当该节点释放了同步状态或者被取消的时候 |
CONDITION | 值为-2,节点在等待队列中,节点线程等待在condition上,当其他线程对condition调用了signal()方法后,该节点将会从等待队列中转移到同步队列中,加入到对同步状态的获取中 |
PROPAGATE | 值为-3,表示下一次共享式同步状态获取将会无条件的传播下去 |
INITIAL | 值为0,初始状态 |
//mode参数值为Node.EXCLUSIVE,表明节点的状态正在等待获取锁
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;
//尾节点不为空,则将node的prev指向尾节点,然后cas将尾节点更新为node
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//尾节点为空
enq(node);
return node;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
//队列为空,则创造一个节点作为头结点,头结点、尾节点指向此此节点,然后再次循环
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
//尾节点不为空,则将node的prev指向尾节点,然后cas将尾节点更新为node
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
acquireQueued解析
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
//获取node的前置节点,如果是头结点,则尝试更新同步状态。
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
//更新同步状态成功,将node设置为头结点
setHead(node);
//将node的前置节点移出队列
p.next = null; // help GC
failed = false;
return interrupted;
}
//node的前置节点不是头结点,则shouldParkAfterFailedAcquire判断node是否应该阻塞,若是,parkAndCheckInterrupt阻塞node节点。
//若node的前置节点是头结点,但更新状态同步失败,则shouldParkAfterFailedAcquire不成立,继续死循环自旋。
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//node已经成功更新同步状态,获得了锁,则清空node的线程信息、前置节点信息。
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
//判断node是否应该阻塞
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
//判断node前置节点的状态值,若为signal,则返回true,node阻塞。
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.
*/
//若node前置节点已取消,则继续向前遍历,找到合适的前置节点。
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.
*/
//将前置节点的状态值设为sigal,下次循环进来,则可以阻塞节点。
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
通过对上述方法的分析,当有多个线程尝试获取锁时,由于cas操作,只能有一个线程更新同步状态成功,其余的线程都需要进入同步队列中排队,会发现队列中,头结点都将是成功获取锁的节点,头结点的后继节点则开始自旋尝试获取锁,一旦获取成功,头结点出队列,后继节点变为头结点,其他节点则继续阻塞。
那么问题来了,已经阻塞了的节点如何被唤醒,继续自旋?
情况一是获得锁的节点释放锁,会唤醒后继节点;
情况二是节点由于中断被取消,会唤醒后继节点;
情况一代码:
public void unlock() {
sync.release(1);
}
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) {
//state状态值-1,同一线程连续多次获得锁,即可重入锁,就是累计加1,释放锁的时候有累计减1,直到state为0
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;
}
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);
}
情况二代码:
private void cancelAcquire(Node node) {
// Ignore if node doesn't exist
if (node == null)
return;
//1. node不再关联到任何线程
node.thread = null;
//2. 跳过被cancel的前继node,找到一个有效的前继节点pred
// Skip cancelled predecessors
Node pred = node.prev;
while (pred.waitStatus > 0)
node.prev = pred = pred.prev;
// predNext is the apparent node to unsplice. CASes below will
// fail if not, in which case, we lost race vs another cancel
// or signal, so no further action is necessary.
Node predNext = pred.next;
//3. 将node的waitStatus置为CANCELLED
// Can use unconditional write instead of CAS here.
// After this atomic step, other Nodes can skip past us.
// Before, we are free of interference from other threads.
node.waitStatus = Node.CANCELLED;
//4. 如果node是tail,更新tail为pred,并使pred.next指向null
// If we are the tail, remove ourselves.
if (node == tail && compareAndSetTail(node, pred)) {
compareAndSetNext(pred, predNext, null);
} else {
// If successor needs signal, try to set pred's next-link
// so it will get one. Otherwise wake it up to propagate.
//
int ws;
//5. 如果node既不是tail,又不是head的后继节点
//则将node的前继节点的waitStatus置为SIGNAL
//并使node的前继节点指向node的后继节点(相当于将node从队列中删掉了)
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 {
//6. 如果node是head的后继节点,则直接唤醒node的后继节点
unparkSuccessor(node);
}
node.next = node; // help GC
}
}