1.ReentrantLock是什么?干啥用?
ReentrantLock是一种基于AQS框架的应用实现,是JDK中的一种线程并发访问的同步手段,它的功能类似于synchronized是一种互斥锁,可以保证线程安全。
2.ReentrantLock代码实现
代码不急着看,咱们先了解,ReentrantLock的功能模型。下图应该算是java中锁的通用模型了。mesa管程模型。
ReentrantLock整体上就是按这个模型实现。了解上图,ReentrantLock就很好理解。
2.1 代码实现
我们直接看类结构。
1. ReentrantLock构造,分无参,有参。默认的无参构造,实现的是非公平锁。
2. ReentrantLock内部,定义了一个抽象类Sync,继承了抽象类AbstractQueuedSynchronizer,也就是常说的AQS。
3. 2个内部类NonfairSync,FairSync实现了此抽象类。
4. 提供lock, tryLock, unLock, lockInterruptibly等方法。
篇幅有限,重点学习一下公平锁的实现
//lock进来
public final void acquire(int arg) {
if (
//尝试获取锁
(1)!tryAcquire(arg) &&
//入队
(3)acquireQueued((2)addWaiter(Node.EXCLUSIVE)
, arg))
selfInterrupt();
}
(1)protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
// c==0 当前无锁,可以加锁
if (
//大概意思就是,
//判断当前线程是不是等待队列的头结点是为false。
//如果没有等待队列,直接返回false
!hasQueuedPredecessors() &&
//CAS上锁
compareAndSetState(0, acquires)) {
//设置上锁线程为当前线程
setExclusiveOwnerThread(current);
return true;
}
}
//这步可以看出来reentrantlock也是一个可重入锁,将内部的state值+1
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
(2)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;
}
}
//如果没有队列,咱们就构造一个。
(2.1)enq(node);
return node;
}
(2.1)private Node enq(final Node node) {
//这边可以看出,什么叫不死不休。哎,咱死循环保证你能搞出一个队列!
for (;;) {
Node t = tail;
//没有屁股那你肯定也没头,我就给你搞个头
//(注意这边可以学习一下,单体并发的情况,如何构建一个队列)
if (t == null) { // Must initialize
if (compareAndSetHead(new Node()))
tail = head;
} else {
//现在有个头了,再把你屁股按上。
node.prev = t;
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
(3)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 ((3.1)shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
(3.1) 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;
}