基本概念
-
ReentrantLock是一个可重入的互斥锁,又被称为独占锁
-
ReentrantLock底层使用CAS+AQS队列来实现
-
ReentRantLock是JDK提供的API,加锁和解锁都是显式的,需要手动加锁和释放锁,使用过后必须释放锁
-
提供了无条件的,可轮询的,定时的以及可中断的锁获取操作
-
可以自由设定公平锁和非公平锁
-
排它锁,在同于时刻只允许一个线程进行访问
-
等待可中断:指持有锁的线程长期不释放锁时,正在等待的线程可以选择放弃等待而处理其他事情,可终端特性对处理执行时间非常长的同步块很有帮助
公平锁和非公平锁
公平锁是指多个线程在等待同一个锁的时候,必须根据先来后到,先申请锁的线程先获得锁,非公平锁无法保证这一点,在锁被释放的时候,每一个等待的线程都会被唤醒然后有机会获得锁,如synchronized,ReentrantLock在默认时非公平的,但是也可以通过构造使用公平锁,但是公平锁的性能比较低,会影响吞吐量
可重入锁
Synchronized和ReentrantLock区别
- synchronized时Java语法层面的同步,是Java关键字,ReentrantLock时JDK提供的API实现
- Lock需要手动的去加锁释放锁,更加灵活,为了确保能够释放锁,避免造成死锁,要改在finally块中释放锁,而synchronized可以由JVM来确保即便同步代码块异常也能正常被释放
AQS
AQS全称AbstractQueueDSynchronizer,AQS是一个阻塞式锁和相关的同步器工具的框架,可用于构建阻塞锁或者其他相关同步器的基础框架,时Java并发包的基础工具类,通过AQS可以对同步状态原子性管理、线程的阻塞和解除阻塞、队列的管理进行统一的管理
特点:
- 通过 volatile int state属性来表示资源的状态。通过CAS设置state状态,分为独占模式和共享模式,子类需要定义get、set 、cas来维护这个状态来控制如何获取和释放锁
- 提供了基于 FIFO 的等待队列,类似于 Monitor 的 EntryList,表示排队等待锁的线程,队列头节点称为“哨兵节点”,其他的节点与等待线程关联每个节点维护一个等待状态waitStatus
state设计
- state使用volatile配合cas保证其修改时的原子性
- state使用32bit 的int来维护同步状态
主要方法
- tryAcquire:尝试获取锁
- tryRelease:释放锁
- tryAcquireShared:尝试获取共享锁
- tryReleaseShared:共享锁尝试解锁
- isHeldExclusively:
AQS由独占模式和共享模式,独占模式表示锁只会被一个线程单独占用,其他线程必须等待持有线程释放锁之后才能获取这个锁,如ReentrantLock就是独占锁。 共享模式表示多个线程获取同一个锁的时候可能会成功,ReadLock就采用的时共享模式
独占模式通过 acquire 和 release 方法获取和释放锁,共享模式通过 acquireShared 和 releaseShared 方法获取和释放锁。
源码分析
首先看一下构造方法,ReentranLock有两个构造方法
//默认构造,非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}
//通过boolean值控制 FairSync时公平锁
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
先看一下默认的非公平锁,我们可以看到通过默认构造创建了一个NonfairSync对象
加锁流程源码
static final class NonfairSync extends Sync {
private static final long serialVersionUID = 7316153563782823691L;
final void lock() {
//加锁时通过CAS尝试将state由0改为1,如果成功就代表加锁成功
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread());
else
//设置失败,进行加入同步队列准备
acquire(1);
}
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
}
abstract static class Sync extends AbstractQueuedSynchronizer
NonfairSync 继承自 AQS
CAS加锁失败进入acquire()方法
public final void acquire(int arg) {
//这里再次尝试获取锁
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
再次尝试加锁,进入 nonfairTryAcquire() 逻辑
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//状态state=0,即在这段时间内 锁的所有者把锁释放了
if (c == 0) {
//通过cas来获得而不去检查AQS队列,体现了非公平性
if (compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
//如果状态state不等于0,有线程正在占用锁,检查当前线程是否等于获得锁的线程,相等则表示发生了锁重入
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;
}
tryAcquire 尝试加锁失败后会进入addWaiter() 这里会构造一个Node队列
private Node addWaiter(Node mode) {
// 将当前线程关联到一个 Node 对象上, 模式为独占模式
Node node = new Node(Thread.currentThread(), mode);
// 如果 tail 不为 null, cas 尝试将 Node 对象加入 AQS 队列尾部
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
// 双向链表
pred.next = node;
return node;
}
}
// 尝试将 Node 加入 AQS, 进入
enq(node);
return node;
}
private Node enq(final Node node) {
for (;;) {
Node t = tail;
if (t == null) { // Must initialize
//节点为空 cas设置头节点为头节点
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
// cas 尝试将 Node 对象加入 AQS 队列尾部
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
Node对象:
- volatile int waitStatus 属性,其中 0 为默认正常状态
- CANCELLED 表示线程已取消
- SIGNAL 表示线程阻塞需要唤醒
- CONDITION 表示线程正在等待
- PROPAGATE 表示后继节点会传播唤醒操作,只会在共享模式下起作用
acquireQueued()方法
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
//for循环尝试去获得锁
for (;;) {
final Node p = node.predecessor();
//前置节点为 head,表示轮到当前线程了,尝试cas加锁成功
if (p == head && tryAcquire(arg)) {
// 获取成功, 设置自己为 head
setHead(node);
//上一个节点help GC
p.next = null; // help GC
failed = false;
//返回中断标记
return interrupted;
}
//shouldParkAfterFailedAcquire方法会将前驱node,即head的waitStatus改为-1
if (shouldParkAfterFailedAcquire(p, node) &&
//park进入等待状态此时改Node的状态会被设置为SIGNAL
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
//获取前置节点的状态
int ws = pred.waitStatus;
//如果前置节点都在阻塞返回true,进入parkAndCheckInterrupt让当前节点也进入阻塞状态
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) {
前置节点被取消了, 那么重构删除前面所有取消的节点,
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
// 这次还没有阻塞
// 但下次如果重试不成功, 则需要阻塞,这时需要设置上一个节点状态为 Node.SIGNAL
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
解锁流程源码
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减去releases
int c = getState() - releases;
//判断当前线程是不是锁的持有者
if (Thread.currentThread() != getExclusiveOwnerThread())
//如果不是当前锁的所有者,就抛出异常
throw new IllegalMonitorStateException();
boolean free = false;
//如果当前线程释放锁之后,state为0,表示锁没有重入。然后将锁的所有者设置为null,返回true,去唤醒其他线程,如果释放锁后state不等于0那就代表有重入,当钱锁还没有释放
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.
*/
// 如果状态为 Node.SIGNAL 尝试重置状态为 0
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.
*/
//找到需要 unpark 的节点, 但本节点从 AQS 队列中脱离, 是由唤醒节点完成的
Node s = node.next;
//不考虑已取消的节点, 从 AQS 队列从后至前找到队列最前面需要 unpark 的节点
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);
}
公平锁实现
ReentrantLock可以通过有参构造实现公平锁,FairSync就是公平锁的实现
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
final void lock() {
acquire(1);
}
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
//公平锁和非公平锁的主要实现就在这里
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//这里判断锁是否已经被释放state==0就代表锁被释放
if (c == 0) {
//首先去检查AQS队列中是否有前驱节点,没有前驱节点才去竞争,这就是公平锁公平的体现
if (!hasQueuedPredecessors() &&
//cas去获取锁
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
//发生锁重入 state+1
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}
可重入原理
通过加锁源码可以知道,ReentrantLock在加锁的时候,如果已经获得了锁,就会判断获得锁的线程是否是当前线程,如果是就会对state状态+1,解锁的时候每解一次state就会-1,只有state减为0了,锁才会释放成功
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()) {
///获得锁的线程为当前线程,state+1
int nextc = c + acquires;
if (nextc < 0) // overflow
throw new Error("Maximum lock count exceeded");
setState(nextc);
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 == 0才回去释放锁
if (c == 0) {
free = true;
setExclusiveOwnerThread(null);
}
setState(c);
return free;
}
可中断模式
ReentrantLock的 lockInterruptibly() 方法给我们提供了可中断的锁获取方式,通过这个方法加锁,一旦监测到中断状态,底层直接抛出中断异常,由上层调用者区去处理中断。
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
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())
//如果在park的过程中发生中断,就会抛出异常,不会再进行循环
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
不可中断模式
在此模式下,即使它被打断,仍会驻留在 AQS 队列中,一直要等到获得锁后方能得知自己被打断了,一旦监测到中断状态,则中断当前线程。
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
//清除打断标记
return Thread.interrupted();
}