当前位置: 移动技术网 > IT编程>开发语言>Java > ReentrantLock源码详解--公平锁、非公平锁

ReentrantLock源码详解--公平锁、非公平锁

2019年07月19日  | 移动技术网IT编程  | 我要评论
问题 (1)重入锁是什么? (2)reentrantlock如何实现重入锁? (3)reentrantlock为什么默认是非公平模式? (4)reentrant

问题

(1)重入锁是什么?

(2)reentrantlock如何实现重入锁?

(3)reentrantlock为什么默认是非公平模式?

(4)reentrantlock除了可重入还有哪些特性?

简介

reentrant = re + entrant,re是重复、又、再的意思,entrant是enter的名词或者形容词形式,翻译为进入者或者可进入的,所以reentrant翻译为可重复进入的、可再次进入的,因此reentrantlock翻译为重入锁或者再入锁。

重入锁,是指一个线程获取锁之后再尝试获取锁时会自动获取锁。

在java中,除了reentrantlock以外,synchronized也是重入锁。

那么,reentrantlock的可重入性是怎么实现的呢?

继承体系

reentrantlock实现了lock接口,lock接口里面定义了java中锁应该实现的几个方法:

// 获取锁
void lock();
// 获取锁(可中断)
void lockinterruptibly() throws interruptedexception;
// 尝试获取锁,如果没获取到锁,就返回false
boolean trylock();
// 尝试获取锁,如果没获取到锁,就等待一段时间,这段时间内还没获取到锁就返回false
boolean trylock(long time, timeunit unit) throws interruptedexception;
// 释放锁
void unlock();
// 条件锁
condition newcondition();

lock接口中主要定义了 获取锁、尝试获取锁、释放锁、条件锁等几个方法。

源码分析

主要内部类

reentrantlock中主要定义了三个内部类:sync、nonfairsync、fairsync。

abstract static class sync extends abstractqueuedsynchronizer {}
static final class nonfairsync extends sync {}
static final class fairsync extends sync {}

(1)抽象类sync实现了aqs的部分方法;

(2)nonfairsync实现了sync,主要用于非公平锁的获取;

(3)fairsync实现了sync,主要用于公平锁的获取。

在这里我们先不急着看每个类具体的代码,等下面学习具体的功能点的时候再把所有方法串起来。

主要属性

private final sync sync;

主要属性就一个sync,它在构造方法中初始化,决定使用公平锁还是非公平锁的方式获取锁。

主要构造方法

// 默认构造方法
public reentrantlock() {
sync = new nonfairsync();
}
// 自己可选择使用公平锁还是非公平锁
public reentrantlock(boolean fair) {
sync = fair ? new fairsync() : new nonfairsync();
}

(1)默认构造方法使用的是非公平锁;

(2)第二个构造方法可以自己决定使用公平锁还是非公平锁;

上面我们分析了reentrantlock的主要结构,下面我们跟着几个主要方法来看源码。

lock()方法

彤哥贴心地在每个方法的注释都加上方法的来源。

1.公平锁

这里我们假设reentrantlock的实例是通过以下方式获得的:

reentrantlock reentrantlock = new reentrantlock(true);

下面的是加锁的主要逻辑:

// reentrantlock.lock()
public void lock() {
// 调用的sync属性的lock()方法
// 这里的sync是公平锁,所以是fairsync的实例
sync.lock();
}
// reentrantlock.fairsync.lock()
final void lock() {
// 调用aqs的acquire()方法获取锁
// 注意,这里传的值为1
acquire(1);
}
// abstractqueuedsynchronizer.acquire()
public final void acquire(int arg) {
// 尝试获取锁
// 如果失败了,就排队
if (!tryacquire(arg) &&
// 注意addwaiter()这里传入的节点模式为独占模式
acquirequeued(addwaiter(node.exclusive), arg))
selfinterrupt();
}
// reentrantlock.fairsync.tryacquire()
protected final boolean tryacquire(int acquires) {
// 当前线程
final thread current = thread.currentthread();
// 查看当前状态变量的值
int c = getstate();
// 如果状态变量的值为0,说明暂时还没有人占有锁
if (c == 0) {
// 如果没有其它线程在排队,那么当前线程尝试更新state的值为1
// 如果成功了,则说明当前线程获取了锁
if (!hasqueuedpredecessors() &&
compareandsetstate(0, acquires)) {
// 当前线程获取了锁,把自己设置到exclusiveownerthread变量中
// exclusiveownerthread是aqs的父类abstractownablesynchronizer中提供的变量
setexclusiveownerthread(current);
// 返回true说明成功获取了锁
return true;
}
}
// 如果当前线程本身就占有着锁,现在又尝试获取锁
// 那么,直接让它获取锁并返回true
else if (current == getexclusiveownerthread()) {
// 状态变量state的值加1
int nextc = c + acquires;
// 如果溢出了,则报错
if (nextc < 0)
throw new error("maximum lock count exceeded");
// 设置到state中
// 这里不需要cas更新state
// 因为当前线程占有着锁,其它线程只会cas把state从0更新成1,是不会成功的
// 所以不存在竞争,自然不需要使用cas来更新
setstate(nextc);
// 当线程获取锁成功
return true;
}
// 当前线程尝试获取锁失败
return false;
}
// abstractqueuedsynchronizer.addwaiter()
// 调用这个方法,说明上面尝试获取锁失败了
private node addwaiter(node mode) {
// 新建一个节点
node node = new node(thread.currentthread(), mode);
// 这里先尝试把新节点加到尾节点后面
// 如果成功了就返回新节点
// 如果没成功再调用enq()方法不断尝试
node pred = tail;
// 如果尾节点不为空
if (pred != null) {
// 设置新节点的前置节点为现在的尾节点
node.prev = pred;
// cas更新尾节点为新节点
if (compareandsettail(pred, node)) {
// 如果成功了,把旧尾节点的下一个节点指向新节点
pred.next = node;
// 并返回新节点
return node;
}
}
// 如果上面尝试入队新节点没成功,调用enq()处理
enq(node);
return node;
}
// abstractqueuedsynchronizer.enq()
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;
// cas更新尾节点为新节点
if (compareandsettail(t, node)) {
// 成功了,则设置旧尾节点的下一个节点为新节点
t.next = node;
// 并返回旧尾节点
return t;
}
}
}
}
// abstractqueuedsynchronizer.acquirequeued()
// 调用上面的addwaiter()方法使得新节点已经成功入队了
// 这个方法是尝试让当前节点来获取锁的
final boolean acquirequeued(final node node, int arg) {
// 失败标记
boolean failed = true;
try {
// 中断标记
boolean interrupted = false;
// 自旋
for (;;) {
// 当前节点的前一个节点
final node p = node.predecessor();
// 如果当前节点的前一个节点为head节点,则说明轮到自己获取锁了
// 调用reentrantlock.fairsync.tryacquire()方法再次尝试获取锁
if (p == head && tryacquire(arg)) {
// 尝试获取锁成功
// 这里同时只会有一个线程在执行,所以不需要用cas更新
// 把当前节点设置为新的头节点
sethead(node);
// 并把上一个节点从链表中删除
p.next = null; // help gc
// 未失败
failed = false;
return interrupted;
}
// 是否需要阻塞
if (shouldparkafterfailedacquire(p, node) &&
// 真正阻塞的方法
parkandcheckinterrupt())
// 如果中断了
interrupted = true;
}
} finally {
// 如果失败了
if (failed)
// 取消获取锁
cancelacquire(node);
}
}
// abstractqueuedsynchronizer.shouldparkafterfailedacquire()
// 这个方法是在上面的for()循环里面调用的
// 第一次调用会把前一个节点的等待状态设置为signal,并返回false
// 第二次调用才会返回true
private static boolean shouldparkafterfailedacquire(node pred, node node) {
// 上一个节点的等待状态
// 注意node的waitstatus字段我们在上面创建node的时候并没有指定
// 也就是说使用的是默认值0
// 这里把各种等待状态再贴出来
//static final int cancelled = 1;
//static final int signal = -1;
//static final int condition = -2;
//static final int propagate = -3;
int ws = pred.waitstatus;
// 如果等待状态为signal(等待唤醒),直接返回true
if (ws == node.signal)
return true;
// 如果前一个节点的状态大于0,也就是已取消状态
if (ws > 0) {
// 把前面所有取消状态的节点都从链表中删除
do {
node.prev = pred = pred.prev;
} while (pred.waitstatus > 0);
pred.next = node;
} else {
// 如果前一个节点的状态小于等于0,则把其状态设置为等待唤醒
// 这里可以简单地理解为把初始状态0设置为signal
// condition是条件锁的时候使用的
// propagate是共享锁使用的
compareandsetwaitstatus(pred, ws, node.signal);
}
return false;
}
// abstractqueuedsynchronizer.parkandcheckinterrupt()
private final boolean parkandcheckinterrupt() {
// 阻塞当前线程
// 底层调用的是unsafe的park()方法
locksupport.park(this);
// 返回是否已中断
return thread.interrupted();
}

下面我们看一下主要方法的调用关系,可以跟着我的 → 层级在脑海中大概过一遍每个方法的主要代码:

reentrantlock#lock()
->reentrantlock.fairsync#lock() // 公平模式获取锁
->abstractqueuedsynchronizer#acquire() // aqs的获取锁方法
->reentrantlock.fairsync#tryacquire() // 尝试获取锁
->abstractqueuedsynchronizer#addwaiter() // 添加到队列
->abstractqueuedsynchronizer#enq() // 入队
->abstractqueuedsynchronizer#acquirequeued() // 里面有个for()循环,唤醒后再次尝试获取锁
->abstractqueuedsynchronizer#shouldparkafterfailedacquire() // 检查是否要阻塞
->abstractqueuedsynchronizer#parkandcheckinterrupt() // 真正阻塞的地方

获取锁的主要过程大致如下:

(1)尝试获取锁,如果获取到了就直接返回了;

(2)尝试获取锁失败,再调用addwaiter()构建新节点并把新节点入队;

(3)然后调用acquirequeued()再次尝试获取锁,如果成功了,直接返回;

(4)如果再次失败,再调用shouldparkafterfailedacquire()将节点的等待状态置为等待唤醒(signal);

(5)调用parkandcheckinterrupt()阻塞当前线程;

(6)如果被唤醒了,会继续在acquirequeued()的for()循环再次尝试获取锁,如果成功了就返回;

(7)如果不成功,再次阻塞,重复(3)(4)(5)直到成功获取到锁。

以上就是整个公平锁获取锁的过程,下面我们看看非公平锁是怎么获取锁的。

2.非公平锁

// reentrantlock.lock()
public void lock() {
sync.lock();
}
// reentrantlock.nonfairsync.lock()
// 这个方法在公平锁模式下是直接调用的acquire(1);
final void lock() {
// 直接尝试cas更新状态变量
if (compareandsetstate(0, 1))
// 如果更新成功,说明获取到锁,把当前线程设为独占线程
setexclusiveownerthread(thread.currentthread());
else
acquire(1);
}
// reentrantlock.nonfairsync.tryacquire()
protected final boolean tryacquire(int acquires) {
// 调用父类的方法
return nonfairtryacquire(acquires);
}
// reentrantlock.sync.nonfairtryacquire()
final boolean nonfairtryacquire(int acquires) {
final thread current = thread.currentthread();
int c = getstate();
if (c == 0) {
// 如果状态变量的值为0,再次尝试cas更新状态变量的值
// 相对于公平锁模式少了!hasqueuedpredecessors()条件
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;
}

相对于公平锁,非公平锁加锁的过程主要有两点不同:

(1)一开始就尝试cas更新状态变量state的值,如果成功了就获取到锁了;

(2)在tryacquire()的时候没有检查是否前面有排队的线程,直接上去获取锁才不管别人有没有排队呢;

总的来说,相对于公平锁,非公平锁在一开始就多了两次直接尝试获取锁的过程。

lockinterruptibly()方法

支持线程中断,它与lock()方法的主要区别在于lockinterruptibly()获取锁的时候如果线程中断了,会抛出一个异常,而lock()不会管线程是否中断都会一直尝试获取锁,获取锁之后把自己标记为已中断,继续执行自己的逻辑,后面也会正常释放锁。

题外话:

线程中断,只是在线程上打一个中断标志,并不会对运行中的线程有什么影响,具体需要根据这个中断标志干些什么,用户自己去决定。

比如,如果用户在调用lock()获取锁后,发现线程中断了,就直接返回了,而导致没有释放锁,这也是允许的,但是会导致这个锁一直得不到释放,就出现了死锁。

lock.lock();
if (thread.currentthread().interrupted()) {
return ;
}
lock.unlock();

当然,这里只是举个例子,实际使用肯定是要把lock.lock()后面的代码都放在try...finally...里面的以保证锁始终会释放,这里主要是为了说明线程中断只是一个标志,至于要做什么完全由用户自己决定。

trylock()方法

尝试获取一次锁,成功了就返回true,没成功就返回false,不会继续尝试。

// reentrantlock.trylock()
public boolean trylock() {
// 直接调用sync的nonfairtryacquire()方法
return sync.nonfairtryacquire(1);
}
// reentrantlock.sync.nonfairtryacquire()
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;
}

trylock()方法比较简单,直接以非公平的模式去尝试获取一次锁,获取到了或者锁本来就是当前线程占有着就返回true,否则返回false。

trylock(long time, timeunit unit)方法

尝试获取锁,并等待一段时间,如果在这段时间内都没有获取到锁,就返回false。

// reentrantlock.trylock()
public boolean trylock(long timeout, timeunit unit)
throws interruptedexception {
// 调用aqs中的方法
return sync.tryacquirenanos(1, unit.tonanos(timeout));
}
// abstractqueuedsynchronizer.tryacquirenanos()
public final boolean tryacquirenanos(int arg, long nanostimeout)
throws interruptedexception {
// 如果线程中断了,抛出异常
if (thread.interrupted())
throw new interruptedexception();
// 先尝试获取一次锁
return tryacquire(arg) ||
doacquirenanos(arg, nanostimeout);
}
// abstractqueuedsynchronizer.doacquirenanos()
private boolean doacquirenanos(int arg, long nanostimeout)
throws interruptedexception {
// 如果时间已经到期了,直接返回false
if (nanostimeout <= 0l)
return false;
// 到期时间
final long deadline = system.nanotime() + nanostimeout;
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 true;
}
nanostimeout = deadline - system.nanotime();
// 如果到期了,就直接返回false
if (nanostimeout <= 0l)
return false;
// spinfortimeoutthreshold = 1000l;
// 只有到期时间大于1000纳秒,才阻塞
// 小于等于1000纳秒,直接自旋解决就得了
if (shouldparkafterfailedacquire(p, node) &&
nanostimeout > spinfortimeoutthreshold)
// 阻塞一段时间
locksupport.parknanos(this, nanostimeout);
if (thread.interrupted())
throw new interruptedexception();
}
} finally {
if (failed)
cancelacquire(node);
}
}

trylock(long time, timeunit unit)方法在阻塞的时候加上阻塞时间,并且会随时检查是否到期,只要到期了没获取到锁就返回false。

unlock()方法

释放锁。

// java.util.concurrent.locks.reentrantlock.unlock()
public void unlock() {
sync.release(1);
}
// java.util.concurrent.locks.abstractqueuedsynchronizer.release
public final boolean release(int arg) {
// 调用aqs实现类的tryrelease()方法释放锁
if (tryrelease(arg)) {
node h = head;
// 如果头节点不为空,且等待状态不是0,就唤醒下一个节点
// 还记得waitstatus吗?
// 在每个节点阻塞之前会把其上一个节点的等待状态设为signal(-1)
// 所以,signal的准确理解应该是唤醒下一个等待的线程
if (h != null && h.waitstatus != 0)
unparksuccessor(h);
return true;
}
return false;
}
// java.util.concurrent.locks.reentrantlock.sync.tryrelease
protected final boolean tryrelease(int releases) {
int c = getstate() - releases;
// 如果当前线程不是占有着锁的线程,抛出异常
if (thread.currentthread() != getexclusiveownerthread())
throw new illegalmonitorstateexception();
boolean free = false;
// 如果状态变量的值为0了,说明完全释放了锁
// 这也就是为什么重入锁调用了多少次lock()就要调用多少次unlock()的原因
// 如果不这样做,会导致锁不会完全释放,别的线程永远无法获取到锁
if (c == 0) {
free = true;
// 清空占有线程
setexclusiveownerthread(null);
}
// 设置状态变量的值
setstate(c);
return free;
}
private void unparksuccessor(node node) {
// 注意,这里的node是头节点

// 如果头节点的等待状态小于0,就把它设置为0
int ws = node.waitstatus;
if (ws < 0)
compareandsetwaitstatus(node, ws, 0);
// 头节点的下一个节点
node s = node.next;
// 如果下一个节点为空,或者其等待状态大于0(实际为已取消)
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);
}

释放锁的过程大致为:

(1)将state的值减1;

(2)如果state减到了0,说明已经完全释放锁了,唤醒下一个等待着的节点;

彩蛋

为什么reentrantlock默认采用的是非公平模式?

答:因为非公平模式效率比较高。

为什么非公平模式效率比较高?

答:因为非公平模式会在一开始就尝试两次获取锁,如果当时正好state的值为0,它就会成功获取到锁,少了排队导致的阻塞/唤醒过程,并且减少了线程频繁的切换带来的性能损耗。

非公平模式有什么弊端?

答:非公平模式有可能会导致一开始排队的线程一直获取不到锁,导致线程饿死。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网