Java并发编程系列文章
欢迎大家观看我的博客,会不断的修正和更新文章,也欢迎大家一起交流
- Java并发编程系列 | 原子操作的底层原理
- Java并发编程系列 | volatile关键字的底层原理
- Java并发编程系列 | synchronized的锁升级过程
- Java并发编程系列 | 线程池原理详解
- Java并发编程系列 | FutureTask原理详解
- Java并发编程系列 | AQS之条件队列的原理
AQS之ReentrantLock原理详解
ReentrantLock简介
ReentrantLock是java在api层面上实现的锁,有公平和非公平的实现,而它的底层实现就是使用的AQS,AQS是很多锁的实现,或者信号量的实现,了解他的原理是很重要的,那么,让我们来看一下,非公平的reentrantLock的实现吧
lock的流程
- 先说一点,在AQS中,有一个代表当前状态的state,为0时表示当前没有线程占用这个锁,每次当一个线程要占用这个锁的时候,都会使用原子操作把state变成1,为的就是确保并发多线程竞争时保证只有一个线程能够更改成功,而如果是要重入,比如一个线程的代码块中嵌套了几个lock、unlock语句,那么每lock一次,这个state就会加1一次。
final void lock() {
//这就是非公平锁,一个线程一进来就直接尝试独占线程,不管队列里面有没有在等待的线程
if (compareAndSetState(0, 1))//尝试CAS操作更改state为1
setExclusiveOwnerThread(Thread.currentThread());//设置当前的线程为独占线程
else
acquire(1);//CAS竞争失败了就使用acquire获取锁
}
我们再看一下acquire是如何获取锁的
public final void acquire(int arg) {
if (!tryAcquire(arg) &&//再次尝试获取锁,非公平锁调用的是nonfairTryAcquire(int acquires)
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))//再次尝试获取锁失败后就把它添加进等待队列
selfInterrupt();
}
先看nonfairTryAcquire(int acquires)的实现
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
//如果state为0,即当前锁没有被占用的话,再次尝试独占线程
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
//如果说这是重入的线程,那么就让state再加acquires,其实就是加1
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
//除开上面两种情况,就是尝试独占锁失败了
return false;
}
调用nonfairTryAcquire(int acquires)独占锁失败后,就会addWaiter(Node.EXCLUSIVE)将其添加进队列尾部,等待执行
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
//如果说这个节点的前一个节点就是头节点了,那么就可以尝试tryAcquire(arg)独占锁了
//没有成功的话说明是前面的节点还在执行,或者被刚来尝试获取锁的线程给抢占了,就会park,
// 等待前一个线程执行完通知它,那么下一个循环就会又开始到这儿尝试独占
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
//尝试独占失败后会去判断或者设置当前节点的等待状态,当waitStatus为Signal的时候,表示当前线程可以进行park了
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())//在这里如果是被打断了,failed就为true
interrupted = true;
}
} finally {
if (failed)//只有被打断了才会到这来
cancelAcquire(node);//设置waitStatus为CANCELED状态,并取消独占和唤醒下一个节点
}
}
unlock的流程
unlock调用的是AQS的release(1)来实现的,那么就来看一下release方法
public final boolean release(int arg) {
//尝试释放锁
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);//给下一个节点unpark信号
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
//释放的话肯定是只能释放自己这个线程的,不然会报错
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
//每次线程重入都会让state加1,而每次会让state减releases,就是减1,
// 当state为0了,就表示当前锁没有被线程独占了
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
private void unparkSuccessor(Node node) {
int ws = node.waitStatus;
if (ws < 0)
compareAndSetWaitStatus(node, ws, 0);
//如果该节点的下个节点为空或者被中断(就是waitStatus被设置为CANCELED)了,重新从尾节点开始找一个节点来unpark
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);//通知这个线程可以尝试去独占锁了
}
lock和lockInterruptibly的区别
1.lock的代码我们已经分析过了,lock是会优先去获取锁的,而不是优先去响应中断,在lock里面当前线程被park之前,
它是不会去响应中断请求的,而当park之后如果有线程中断请求,那么在acquireQueued方法里,他会指示interrupt为true,
并在获取到锁后返回true。
2.在看lockInterruptibly的代码,它会调用acquireInterruptibly(1)来实现,它是优先响应中断的,不是非要先获取到锁了才能响应中断,
并且lock会将中断请求消化掉,lockInterruptibly会抛出一个中断异常出来。
public final void acquireInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())//线程被中断则直接抛出异常
throw new InterruptedException();
if (!tryAcquire(arg))//尝试独占线程
doAcquireInterruptibly(arg);//加入等待队列并等待执行
}
private void doAcquireInterruptibly(int arg)
throws InterruptedException {
final Node node = addWaiter(Node.EXCLUSIVE);//加入等待队列
boolean failed = true;
try {
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
//和lock调用的acquireQueued的区别就在这,被中断了就直接抛出中断异常,
// 不会再等着一定要获取这把锁才会响应中断
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);//被中断了一定是会被执行的
}
}
公平锁和非公平锁
1.上面非公平锁已经分析过了,非公平锁在lock的时候,如果此时锁没有被独占,就会直接去尝试竞争独占这把锁,只有竞争不到了,才会把
等待节点插入队列,它可能会让后来的线程直接竞争到锁,就算队列里面有等待节点,所以它是非公平的。
2.而公平锁呢?它的lock是直接调用acquire加入队列并等待执行,它就不会存在被抢占的情况
final void lock() {
acquire(1);//直接调用acquire
}
acquire方法会调用tryAcquire方法的公平实现,在这里和非公平实现是只有在队列里已经没有等待节点的时候,
才会去尝试竞争独占锁。
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;
}
可重入锁的实现原理
可重入的实现原理也是比较简单的,无论是公平锁还是非公平锁,都是在tryAcquire里实现可重入的,在AQS中有一个state状态,
表示目前占有该锁的线程的数量,如果是同一个线程的话,每lock一次,在tryAcquire里state就会加1一次,而执行unlock的时候,
tryRelease里面每执行一次也会使state减1,通过记录state来实现可重入。