ReentrantLock
1.AQS(AbstractQueudSynchronized)
并发包下的一个基类,抽象队列同步器 alt+7查看类结构
AQS中类重要字段
头节点 尾节点 state线程状态
private transient volatile Node head;
/**
* Tail of the wait queue, lazily initialized. Modified only via
* method enq to add new wait node.
*/
private transient volatile Node tail;
/**
* The synchronization state.
*/
private volatile int state;
AQS中的Node属性
static final class Node {
static final Node SHARED = new Node();
static final Node EXCLUSIVE = null;//是否为独占锁标志
static final int CANCELLED = 1;//说明该节点失效
static final int SIGNAL = -1;//说明该节点的后继节点需要被唤醒
static final int CONDITION = -2;
static final int PROPAGATE = -3;
volatile int waitStatus; //Node对象存储标识的地方
volatile Node prev;
volatile Node next;
volatile Thread thread;//当前Node绑定的线程
Node nextWaiter;
final boolean isShared() {
return nextWaiter == SHARED;
}
//返回前驱节点
final Node predecessor() throws NullPointerException {
Node p = prev;
if (p == null)
throw new NullPointerException();
else
return p;
}
Node() {
}
Node(Thread thread, Node mode) { // Used by addWaiter
this.nextWaiter = mode;
this.thread = thread;
}
Node(Thread thread, int waitStatus) { // Used by Condition
this.waitStatus = waitStatus;
this.thread = thread;
}
}
使用格式
Lock lock = new ReentrantLock();
try{
lock.lock();//加锁操作
}finally{
lock.unlock();
}
2.ReentrantLock非公平锁分析
1.从入口分析
public void lock() {
sync.lock();
}
2.从非公平锁进入
final void lock() {
//通过CAS方法 尝试将state从0修改为1 返回成功则执行
if (compareAndSetState(0, 1))
//将一个属性设置为当前线程,这个属性是AQS父类提供的
setExclusiveOwnerThread(Thread.currentThread());
else
//
acquire(1);
}
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}
//AQS中代码
protected final boolean compareAndSetState(int expect, int update) {
// See below for intrinsics setup to support this
return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
}
3.查看acquire方法
public final void acquire(int arg) {
//tryAcquire是再次尝试获取锁资源,若尝试成功,返回true
//获取锁资源失败后,需要将当前线程封装成一个Node节点,追加到AQS队列中
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
//线程中断
selfInterrupt();
}
4.查看tryAcquire方法
非公平锁中的实现
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//如果state为0;代表可以再次尝试获取锁资源
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");
//赋值state,锁重入成功
setState(nextc);
return true;
}
return false;
}
5.addWaiter方法
获取锁资源失败,封装成Node进入AQS
private Node addWaiter(Node mode) {
//创建Node类,将当前线程封装,设置为排他锁
Node node = new Node(Thread.currentThread(), mode);
//获取当前AQS队列中的尾部节点
Node pred = tail;
if (pred != null) {
//将当前创建的节点prev设置为刚才的AQS的tail
node.prev = pred;
if (compareAndSetTail(pred, node)) {
//将AQS的尾节点next设置为当前节点
pred.next = node;
return node;
}
}
//如果AQS为空,队列中没有NOde
enq(node);
return node;
}
//现在没人排队,我是第一个 ,或者前面CAS设置新的AQS尾节点失败也进入
private Node enq(final Node node) {
//死循环 自旋进行设置
for (;;) {
Node t = tail;
if (t == null) { // 没人排队 进行初始化 创建头节点
//不成功会一直自旋
if (compareAndSetHead(new Node()))
tail = head;
} else {
node.prev = t;
//不成功会一直自旋
if (compareAndSetTail(t, node)) {
t.next = node;
return t;
}
}
}
}
6.查看acquireQueued方法
已经将Node加入了双向队列中,然后执行下面的方法
- 只有前驱节点是头节点才能够尝试获取同步状态
- 头节点是成功获取到同步状态的节点,而头结点的线程释放了同步状态之后,将会唤醒其后继节点,后继节点小于检查自己的前驱节点是否为头节点
- 死循环中 节点自旋获取同步状态
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
//获取当前节点的前驱节点
final Node p = node.predecessor();
//如果当前前驱节点为头节点
//说明当前Node是紧跟着头节点的下一个节点
//所以第二个条件,再次尝试获取锁资源 state从0-1
//刚进来就抢锁,体现其不公平性
if (p == head && tryAcquire(arg)) {
//设置当前节点为head,拿到锁资源了,排队和我没关系了,头节点没有意义
setHead(node);
p.next = null; // 之前的头节点next指向null,可达性没了,回收
failed = false;//修改标识
return interrupted;
}
//保证上一个节点状态为-1,才会将线程挂起,等待唤醒获取锁资源
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())//基于unsafe类的park方法挂起线程
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
//上一个节点的状态
int ws = pred.waitStatus;
//如果上一个节点状态为-1 正确
if (ws == Node.SIGNAL)
return true;
//为1 说明已经失效 需要向前一直找到有效的前驱节点
if (ws > 0) {
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
//前驱节点状态如果为小于-1,将上一个有效节点状态设置为-1
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fN3zZ6em-1657985484594)(C:\Users\zjg\AppData\Roaming\Typora\typora-user-images\image-20220716203721181.png)]
7.释放锁
释放同步状态,唤醒后继节点
需要考虑后续节点出现空节点或者等待状态取消的情况
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
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.
*/
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.
*/
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)
//唤醒s线程
LockSupport.unpark(s.thread);
}
3.共享式同步状态获取分析
共享锁获取与独占锁主要区别是同一时刻能否有多个线程获取到同步状态
一般情况下,读操作能够共享,写操作需要独占式访问
tryAcquireShared返回值大于0时,表示能够获得到同步状态
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
//失败
doAcquireShared(arg);
}
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
//当前节点的前驱为头节点
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
releaseShared释放
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
独占式超时获取同步状态tryAcquireNanos
指定的时间去获取同步状态,成功为true,失败为false
acquireInterruptibly,等待获取同步时,当前线程被中断,会立刻返回
4.重入锁ReentrantLock
支持重进入的锁,表示能够支持一个线程对于资源的重复加锁
获取到锁的线程,能够在再次调用Lock()方法获取锁而不被阻塞
Sync内部类继承了AQS同步器,NonfairSync 与FairSync继承Sync 分公平和非公平 重写了抢锁和释放锁的方式
公平性问题:
- 绝对时间上,先对锁进行获取的请求一定先满足,那么这个锁就是公平的,反之为不公平
- 公平的获取锁,也就是等待时间最长的线程优先获得锁
- ReentrantLock提供了一个构造函数,能够控制是否为公平锁,1为公平,0为不公平
- 公平的锁往往没有非公平的锁效率高,但是能够减少线程饥饿的概率
实现重进入
线程再次获取锁 锁需要去识别获取锁的线程是否为当前占据锁的线程,如果是,再次获取成功
锁的最终释放 线程重复N次获取了锁,随后再第N次释放该锁,state在加锁时会自增,释放时会递减,减为0表示锁已经成功释放
该方法增加了再次获取同步状态的逻辑
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
//如果没有上锁,那么久CAS上锁,设置state为1
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;
}
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;
}
公平锁与非公平锁获取锁的区别
非公平锁获取锁
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
//非公平获取锁
final boolean nonfairTryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
//如果state为0;代表可以再次尝试获取锁资源
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");
//赋值state,锁重入成功
setState(nextc);
return true;
}
return false;
}
公平获取锁
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;
}
不同点
**公平锁会加一个 hasQueuedPredecessors()方法,**用以判断等待队列是否有元素