文章目录
一、如何设计一把独占锁
首先我们需要定义一个状态变量,用来去记录是否加锁(0-未加锁,1-加锁),多个线程在竞争锁的过程为了保证只有一个线程能抢到锁,还需要引入CAS,然后未竞争到锁的线程需要存放到一个队列(数组或者链表中,然后唤醒线程和阻断线程也需要用到Java里面的唤醒等待机制:
1.sychronizd + object.wait()/object.notify()/object.notifyAll,此方案无法唤起具体线程
2.ReentrantLock + condition.await()/condition.signal/signalAll
这两套机制底层用到的阻塞线程和唤醒线程都是通过(LockSupport.part/unpark)去实现的
然后利用Java的模板模式去做入口等待队列、入队出队、修改CAS等逻辑操作
import java.util.concurrent.locks.LockSupport;
public class ParkAndUnparkDemo {
public static void main(String[] args) {
ParkAndUnparkThread myThread = new ParkAndUnparkThread(Thread.currentThread());
myThread.start();
System.out.println("before park");
// 获取许可
LockSupport.park();
System.out.println("after park");
}
}
class ParkAndUnparkThread extends Thread {
private Object object;
public ParkAndUnparkThread(Object object) {
this.object = object;
}
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("before unpark");
// 释放许可
LockSupport.unpark((Thread) object);
System.out.println("after unpark");
}
}
二、管理模型MESA详解
同步等待队列是为了针对互斥场景,而条件等待队列针对同步场景,需要控制线程的顺序
Q1:为什么条件队列的线程要转入同步队列
因为AQS设计的原理是,唤醒线程的时候只需要从同步队列中去唤醒,没必要从两个队列中都去唤醒,会增加复杂度,编程讲的就是一个复用
三、基于MESA规范Java是如何设计AQS的
什么是AQS
java.util.concurrent包中的大多数同步器实现都是围绕着共同的基础行为,比如等待队列、条件队列、独占获取、共享获取等,而这些行为的抽象就是基于AbstractQueuedSynchronizer(简称AQS)实现的,AQS是一个抽象同步框架,可以用来实现一个依赖状态的同步器。
JDK中提供的大多数的同步器如Lock, Latch, Barrier等,都是基于AQS框架来实现的
一般是通过一个内部类Sync继承 AQS
将同步器所有调用都映射到Sync对应的方法
AQS具备的特性:
阻塞等待队列
共享/独占
公平/非公平
可重入
允许中断
AQS核心结构
AQS内部维护属性volatile int state
state表示资源的可用状态
State三种访问方式:
getState()
setState()
compareAndSetState()
定义了两种资源访问方式:
Exclusive-独占,只有一个线程能执行,如ReentrantLock
Share-共享,多个线程可以同时执行,如Semaphore/CountDownLatch
AQS实现时主要实现以下几种方法:
isHeldExclusively():该线程是否正在独占资源。只有用到condition才需要去实现它。
tryAcquire(int):独占方式。尝试获取资源,成功则返回true,失败则返回false。
tryRelease(int):独占方式。尝试释放资源,成功则返回true,失败则返回false。
tryAcquireShared(int):共享方式。尝试获取资源。负数表示失败;0表示成功,但没有剩余可用资源;正数表示成功,且有剩余资源。
tryReleaseShared(int):共享方式。尝试释放资源,如果释放后允许唤醒后续等待结点返回true,否则返回false。
AQS定义两种队列
同步等待队列: 主要用于维护获取锁失败时入队的线程。
条件等待队列: 调用await()的时候会释放锁,然后线程会加入到条件队列,调用signal()唤醒的时候会把条件队列中的线程节点移动到同步队列中,等待再次获得锁。
AQS 定义了5个队列中节点状态:
值为0,初始化状态,表示当前节点在sync队列中,等待着获取锁。
CANCELLED,值为1,表示当前的线程被取消;
SIGNAL,值为-1,表示当前节点的后继节点包含的线程需要运行,也就是unpark;
CONDITION,值为-2,表示当前节点在等待condition,也就是在condition队列中;
PROPAGATE,值为-3,表示当前场景下后续的acquireShared能够得以执行;
同步等待队列
AQS当中的同步等待队列也称CLH队列,CLH队列是Craig、Landin、Hagersten三人发明的一种基于双向链表数据结构的队列,是FIFO先进先出线程等待队列,Java中的CLH队列是原CLH队列的一个变种,线程由原自旋机制改为阻塞机制。
AQS 依赖CLH同步队列来完成同步状态的管理:
1.当前线程如果获取同步状态失败时,AQS则会将当前线程已经等待状态等信息构造成一个节点(Node)并将其加入到CLH同步队列,同时会阻塞当前线程
2.当同步状态释放时,会把首节点唤醒(公平锁),使其再次尝试获取同步状态。
3.通过signal或signalAll将条件队列中的节点转移到同步队列。(由条件队列转化为同步队列)
条件等待队列
AQS中条件队列是使用单向列表保存的,用nextWaiter来连接:
调用await方法阻塞线程;
当前线程存在于同步队列的头结点,调用await方法进行阻塞(从同步队列转化到条件队列)
四、基于AQS手写一把独占锁
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
public class TulingLock extends AbstractQueuedSynchronizer{
@Override
protected boolean tryAcquire(int unused) {
//cas 加锁 state=0
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int unused) {
//释放锁
setExclusiveOwnerThread(null);
setState(0);
return true;
}
public void lock() {
acquire(1);
}
public boolean tryLock() {
return tryAcquire(1);
}
public void unlock() {
release(1);
}
public boolean isLocked() {
return isHeldExclusively();
}
}
五、JUC下独占锁ReentrantLock源码分析
public void buyTicket() {
lock.lock(); // 获取锁
try {
if (tickets > 0) { // 还有票 读
try {
Thread.sleep(10); // 休眠10ms
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "购买了第" + tickets-- + "张票"); //写
//buyTicket();
} else {
System.out.println("票已经卖完了," + Thread.currentThread().getName() + "抢票失败");
}
} finally {
lock.unlock(); // 释放锁
}
}
public void lock() {
sync.lock();
}
选择线程一
做了CAS操作,将状态由0变为1
final void lock() {
if (compareAndSetState(0, 1))//CAS
setExclusiveOwnerThread(Thread.currentThread());//设置属性
else
acquire(1);
}
设置属性,独占线程设置为当前线程
protected final void setExclusiveOwnerThread(Thread thread) {
exclusiveOwnerThread = thread;
}
至此线程1已经加锁成功,现在切换到线程2的断点,加锁失败会进入acquire的逻辑,这里是非公平锁,公平锁没有CAS操作会直接调acquire方法
尝试去获取锁
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
非公平的方式去获取锁
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
此时线程2的状态是1
这里会去判断当前线程2是不是独占线程(此时的独占线程是1),为了重入锁设计的,当线程1再次递归调用的时候,进入if逻辑,那么nextc此时的值为2,继续将线程1的state设置为2;以此类推,3,4…释放锁的时候也需要将state每次减1,最终减到0才能退出重入锁
上述线程2返回为false,会进入队列操作逻辑,首先是addWaiter创建队列
构建了队列对象,将线程2的信息放入,设置waitStatus为0,这个node是一个双向链表,
此时的尾节点是空的,进入enq方法
看注释也知道,插入一个节点到队列,在有必要的时候初始化
/**
* Inserts node into queue, initializing if necessary. See picture above.
* @param node the node to insert
* @return node's predecessor
*/
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;
}
}
}
}
此时尾节点是空的,所以会通过CAS去设置一个空的节点对象到队列的head处,设置成功之后,会将尾节点=头节点(因为是双向链表),这里的初始化操作也是线程安全的,只会有一个线程去初始化队列
/**
* CAS head field. Used only by enq.
*/
private final boolean compareAndSetHead(Node update) {
return unsafe.compareAndSwapObject(this, headOffset, null, update);
}
现在队列已经初始化完毕了,可以往队列中设置节点了,就是上一步循环的new Node();
进入else逻辑,将线程2的前驱节点设置为上一步循环的创建的空节点(建立链表关系)
然后进行了CAS操作,将尾节点设置到线程2上(先有head,然后tail=head,然后tail=线程2),再设置空节点的后置节点是线程2,至此构建了一个空节点和一个线程2节点的双链表结构,此时线程2入队成功
/**
* CAS tail field. Used only by enq.
*/
private final boolean compareAndSetTail(Node expect, Node update) {
return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
}
到此我们只是把线程2入队了,还没有挂起,不然会一直消耗CPU,addWaiter方法返回以后,进入accquiredQueued方法挂起线程
这里获取到线程2的前驱节点,也就是空节点
如果前驱节点是head节点,就可以再次尝试去获取一下锁
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 (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
此时前驱节点的waitStatus=0,设置为Node.SIGNAL = -1
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
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) {
/*
* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
*/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/*
* waitStatus must be 0 or PROPAGATE. Indicate that we
* need a signal, but don't park yet. Caller will need to
* retry to make sure it cannot acquire before parking.
*/
compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
}
return false;
}
返回之后,继续循环,会再次尝试去拿锁,毕竟阻塞需要系统间上下文调度比较耗费性能,CAS是系统间的指令操作,不存在系统调度,没有CPU上下文切换
再次进入此方法时候,线程2的状态已经是-1了,返回true,满足阻塞的条件了
park可以被中断
/**
* Convenience method to park and then check if interrupted
*
* @return {@code true} if interrupted
*/
private final boolean parkAndCheckInterrupt() {
LockSupport.park(this);
return Thread.interrupted();
}
至此线程被挂起
现在回到线程1,去释放锁
将线程1的状态减1,设置当前占用线程为null
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;
}
接下来就是之前队列的head节点出队的操作,唤醒下一节点
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
先把waistatus由-1变为0,然后拿到下一节点即线程2,调用LockSupport.unpark(s.thread);去唤醒
/**
* Wakes up node's successor, if one exists.
*
* @param node the node
*/
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)
LockSupport.unpark(s.thread);
}
此时线程2继续执行,进入if逻辑
for (;;) {
final Node p = node.predecessor();
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
设置head为当前线程2的节点,节点trread设置为null,前驱标识也置空
/**
* Sets head of queue to be node, thus dequeuing. Called only by
* acquire methods. Also nulls out unused fields for sake of GC
* and to suppress unnecessary signals and traversals.
*
* @param node the node
*/
private void setHead(Node node) {
head = node;
node.thread = null;
node.prev = null;
}
再把next关系删掉,被垃圾回收期GC掉
if (p == head && tryAcquire(arg)) {
setHead(node);
p.next = null; // help GC
failed = false;
return interrupted;
}
后面就是线程2 可以加锁成功了