概述
- ReetrantLock是Lock的实现类
- ReetrantLock可以创建公平锁,非公平锁,默认是非公平锁
- ReetrantLock底层结构是CAS+volatile+Node+Queue
- 可被重入,相关代码是AQS的**getState()**方法
源码
入口
//入口方法,作用是加锁
public void lock() {
sync.lock();
}
// sync.lock()有俩个实现,FairSync.lock 公平锁 / NonfairSync.lock 非公平锁
abstract void lock();
非公平锁
final void lock() {
//CAS去比较更新
if (compareAndSetState(0, 1))
//当前线程会设置为独占
setExclusiveOwnerThread(Thread.currentThread());
else
//尝试加锁
acquire(1);
}
/**
* 成功返回,失败排队
* 可能反复阻塞和解除阻塞
*/
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
tryACquire
/**
* 非公平锁的tryAcquire实现
*/
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
//调用AQS的getState()方法,代表加锁次数,使用volatile修饰
int c = getState();
if (c == 0) {
//加锁成功,线程设置独占
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//判断是否可重入,重入则state+1
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
/**
* 在tryAcquire获取锁失败,后续执行接下来方法,进行放入阻塞队列
*/
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
//tail 队列的尾节点
Node pred = tail;
if (pred != null) {
node.prev = pred;
//利用CAS尝试快速入队
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
//快速入队失败走这里,进行正常的创建节点相关
enq(node);
return node;
}
/**
* 节点入队
*/
private Node enq(final Node node) {
for (;;) {
Node t = tail;
//为空则重新创建NOde,并不是要入队的节点加入队列
if (t == null) {
if (compareAndSetHead(new Node()))
tail = head;
} else {
//队列不为空,要入队的节点插入到队尾,然后返回前节点
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
acqireQueued
/**
* 不间断的方式去获取队列中的线程
*/
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;
}
//判断锁失败后,是否需要park,如果需要同步监听判断
//park是调用LookSupport.park 等待许可
//unpark 颁发许可/park 等待许可 许可不可叠加/unpark可先park调用
//相对于wail/notify 解耦线程之间的同步,不需要关心彼此状态,没有时序问题
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
公平锁
final void lock() {
//与非公平锁不同,直接设置state的值为1
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
//如果没有其他线程排在当前线程前,尝试加锁,成功则state+1
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;
}
解锁
public void unlock() {
//传入进去 会与state做减法,判断锁是否占用
sync.release(1);
}
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
//唤醒其他线程 unpark/park上面简单介绍,可百度更详细内容
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;
}