JUC源码解析
1、Atomic包
原子性操作示例
public final boolean compareAndSet(int expect, int update) {
return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
}
2、Locks源码
2.1 ReentrantLock -可重入锁
概念
基于AQS实现,可重入锁
使用场景 - 写多读少
核心变量和构造器
核心变量
// 锁的同步器
private final Sync sync;
abstract static class Sync extends AbstractQueuedSynchronizer{
}
构造器
// 无参构造,默认就是非公平锁
public ReentrantLock() {
sync = new NonfairSync();
}
// 可以选择用公平锁还是非公平锁
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
内部类
// 同步代码块
abstract static class Sync extends AbstractQueuedSynchronizer{
}
// 非公平锁
static final class NonfairSync extends Sync{
}
// 公平锁
static final class FairSync extends Sync {
}
核心方法
lock方法
public void lock() {
sync.lock();
}
公平锁 - tryAcquire
final void lock() {
// AQS方法,虽有暴露模板方法tryAcquire
acquire(1);
}
// 尝试获取锁
protected final boolean tryAcquire(int acquires) {
// 当前线程
final Thread current = Thread.currentThread();
// 获取当前线程的状态
int c = getState();
// 无锁情况下
if (c == 0) {
if (!hasQueuedPredecessors() && // 查询是否有线程比当前线程获取锁的等待时间更长
compareAndSetState(0, acquires)) {
// cas设置当前状态为acquires
// 设置当前线程为独占互斥锁的拥有者
setExclusiveOwnerThread(current);
return true;
}
}
// 当前线程是是独占互斥锁的拥有者
else if (current == getExclusiveOwnerThread()) {
// 增加重入次数
int nextc = c + acquires;
// 重入次数操作int最大值报错
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
// 设置重入状态
setState(nextc);
// 返回获取锁成功
return true;
}
// 返回获取锁失败
return false;
}
非公平锁 -nonfairTryAcquire
// 非公平锁
final void lock() {
// 直接抢锁
if (compareAndSetState(0, 1))
setExclusiveOwnerThread(Thread.currentThread()); // 抢锁成功把当前线程设置为独占锁拥有者
else
// 抢锁失败,走tryAcquire
acquire(1);
}
// 尝试抢锁
protected final boolean tryAcquire(int acquires) {
return nonfairTryAcquire(acquires);
}
// 非公平锁抢锁
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;
// 重入次数操作int最大值报错
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
// 更新重入次数
setState(nextc);
return true;
}
return false;
}
tryLock方法 - nonfairTryAcquire
// 直接走非公平锁的抢锁逻辑
public boolean tryLock() {
return sync.nonfairTryAcquire(1);
}
unlock方法
tryRelease
public void unlock() {
// AQS方法,子类实现tryRelease放啊
sync.release(1);
}
// 释放锁
protected final boolean tryRelease(int releases) {
// 释放releases个锁状态
int c = getState() - releases;
// 如果不是当前线程持有锁,直接报错
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
// 设置释放状态
boolean free = false;
// 释放到无锁状态
if (c == 0) {
// 设置释放为true
free = true;
// 设置当前独占锁线程拥有者为null
setExclusiveOwnerThread(null);
}
// 更新锁状态
setState(c);
return free;
}
isLock方法
final boolean isLocked() {
// 锁状态不为0
return getState() != 0;
}
2.2 ReentrantReadWriteLock-读写锁
1.核心概念
读写锁切割为读锁和写锁,读多写少的场景,读锁可以并发,写锁与其他锁互斥,写写互斥,读写互斥,读读兼容
1.读锁
就是用于读互斥区中保护变量
2.写锁
就是用于写互斥区中保护变量
3.锁升级
线程获取到读锁,想要释放读锁,获取写锁
1.先释放读锁,后获取写锁(排队)
2.不释放锁持有的读锁,直接获取写锁(非法状态,死锁)
4.锁降级
线程获取到写锁,想要释放写锁,获取读锁
1.先释放写锁,后获取读锁(可能排队)
2.不释放所持有的写多,去获取读锁(非法状态,切记在一个线程中去处理,相当于自己干自己,没有意义,不合理,死锁)
2.核心变量
/** 读锁 */
private final ReentrantReadWriteLock.ReadLock readerLock;
/** 写锁 */
private final ReentrantReadWriteLock.WriteLock writerLock;
/** 同步器 */
final Sync sync;
3.核心构造器
// 无参构造
public ReentrantReadWriteLock() {
// 默认是非公平锁
this(false);
}
// 有参数是否公共
public ReentrantReadWriteLock(boolean fair) {
// 默认非公平锁
sync = fair ? new FairSync() : new NonfairSync();
// 实例化一个读锁
readerLock = new ReadLock(this);
// 实例化一个写锁
writerLock = new WriteLock(this);
}
4.内部类
// 同步器
abstract static class Sync extends AbstractQueuedSynchronizer{
}
// 非公平同步器
static final class NonfairSync extends Sync{
}
// 公平的同步器
static final class FairSync extends Sync {
}
// 读锁
public static class ReadLock implements Lock, java.io.Serializable {
}
// 写锁
public static class WriteLock implements Lock, java.io.Serializable {
}
Sync类的变量
// 锁分为互斥锁和共享锁,分别用int的高低16位代替,高16位为共享锁持有数量,低16位为互斥锁持有数量
// 共享锁位数
static final int SHARED_SHIFT = 16;
// 共享锁单元
static final int SHARED_UNIT = (1 << SHARED_SHIFT); // 1000000000000000
// 锁的最大数量
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1; // 0111111111111111
// 互斥锁的掩码
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1; // 0111111111111111
// 返回当前共享锁的持有数量,数量向右移动16位,变成共享锁的数量
static int sharedCount(int c) {
return c >>> SHARED_SHIFT; }
// 返回当前互斥锁持有的数量,当前数量&00000000000111111111111111得到低16位的数值
static int exclusiveCount(int c) {
return c & EXCLUSIVE_MASK; }
// 第一个获得读锁的线程
private transient Thread firstReader = null;
// 第一个获得读锁的线程持有的锁数量
private transient int firstReaderHoldCount;
// 最后一个成功获得读锁的线程锁持有的数量
private transient HoldCounter cachedHoldCounter;
// 当前线程缓存在threadLocal中持有可重入锁读锁的数量
private transient ThreadLocalHoldCounter readHolds;
5.读锁
1、lock方法
public void lock() {
// AQS共享锁获取方法,子类实现tryAcquireShared
sync.acquireShared(1);
}
// AQS方法,子类实现tryAcquireShared方法
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
tryAcquireShared-获取锁方法
protected final int tryAcquireShared(int unused) {
// 获取当前线程
Thread current = Thread.currentThread();
// 锁状态
int c = getState();
if (exclusiveCount(c) != 0 && // 互斥锁数量不为0
getExclusiveOwnerThread() != current) // 当前线程不是互斥锁拥有者,获取锁失败
return -1;
// 查询共享锁的数量
int r = sharedCount(c);
// 这里基本就是 *** 优化前置 ***
if (!readerShouldBlock() && // 读锁是否应该被阻塞,查看是否有写锁占用
r < MAX_COUNT && // 共享锁数量尚未超过最大值
compareAndSetState(c, c + SHARED_UNIT)) {
// cas添加持有数量1
// 共享锁持有数量为0
if (r == 0) {
// 设置为第一个获取读锁的线程
firstReader = current;
// 设置为第一个获取读锁的线程持有锁数量
firstReaderHoldCount = 1;
} else if (firstReader == current) {
// 如果当前线程就是第一个持有读锁的线程
// 第一个持有读锁的线程持有锁数量增加
firstReaderHoldCount++;
} else {
HoldCounter rh = cachedHoldCounter;
if (rh == null || // 最后一个获得读锁的线程不存在
rh.tid != getThreadId(current)) // 当前线程不是最后一个获得读锁的线程
// 当前线程持有的锁数量赋值给最后一个持有锁的对象
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0) // 最后一个获得锁线程的持有锁数量为0
// 最后一个获得锁线程设置为当前线程
readHolds.set(rh);
// 获取锁数量加1
rh.count++;
}
return 1;
}
// 全面尝试获取共享锁, 跟上面优化前置基本类似
return fullTryAcquireShared(current);
}
final boolean readerShouldBlock() {
// 队列第一个是否互斥锁
return apparentlyFirstQueuedIsExclusive();
}
fullTryAcquireShared方法
final int fullTryAcquireShared(Thread current) {
// 线程计数器
HoldCounter rh = null;
// 死循环获取锁
for (;;) {
int c = getState(); //获取当前锁状态
// 1.判断是否有互斥锁
if (exclusiveCount(c) != 0) {
// 持有互斥搜数量不为0
// 如果持有互斥锁的线程不是当前线程直接获取锁失败,去等待吧
if (getExclusiveOwnerThread() != current)
return -1;
// else we hold the exclusive lock; blocking here
// would cause deadlock.
// 否则我们持有互斥锁, 阻塞在这里将会导致死锁
}
// 2.读应该是不是应该被阻塞
else if (readerShouldBlock()) {
// Make sure we're not acquiring read lock reentrantly
// 第一个获取读锁的线程是当前线程, 保证我们不会重复获取读锁
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
} else {
if (rh == null) {
// 如果线程计数器为空
// 最后一个持有读锁的线程赋值给计数器rh
rh = cachedHoldCounter;
if (rh == null // 最后一个持有读锁的线程为空
|| rh.tid != getThreadId(current)) {
// 最后一个持有读锁的线程不是当前线程
// 赋值为当前线程持有的读锁的计数器
rh = readHolds.get();
if (rh.count == 0) // 如果当前线程持有读锁数量为0
readHolds.remove(); // 移除该线程的读锁计数器
}
}
// 如果持有读锁数量为0返回-1,未获得成功
if (rh.count == 0)
return -1;
}
}
// 3.获取共享锁的数量已经达到最大值,报错异常
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// 4.获取读锁成功,更新读锁数量
if (compareAndSetState(c, c + SHARED_UNIT)) {
// 如果共享锁数量为0
if (sharedCount(c) == 0) {
// 设置当前线程为第一个获取读锁的线程
firstReader = current;
// 更新第一个获取读锁线程的锁数量
firstReaderHoldCount = 1;
} else if (firstReader == current) {
// 当前线程为第一个获取读锁的线程
// 更新第一个线程持有锁数量
firstReaderHoldCount++;
} else {
// 计数器为空,赋值为最后一个获取读锁的线程
if (rh == null)
rh = cachedHoldCounter;
if (rh == null || // 计数器任然为空
rh.tid != getThreadId(current)) // 当前线程不是持有锁的线程
// 当前线程持有重入读锁赋值给计数器
rh = readHolds.get();
else if (rh.count == 0) // 计数器读锁数量为0
// 加到自己当前的线程的threadLocal计数器中
readHolds.set(rh);
// 更新当前线程持有锁的数量
rh.count++;
// 设置缓存的的最后一个获取锁的线程为当前线程
cachedHoldCounter = rh; // cache for release
}
return 1;
}
}
}
readerShouldBlock方法
// 非公平锁
final boolean readerShouldBlock() {
// 看队列第一个是不是写锁
return apparentlyFirstQueuedIsExclusive();
}
// 公平锁,排队
final boolean readerShouldBlock() {
return hasQueuedPredecessors();
}
2、tryLock方法
// Acquires the read lock only if the write lock is not held by another thread at the time of invocation.
// 仅当写锁没有在请求的同时被其他线程持有
public boolean tryLock() {
return sync.tryReadLock();
}
tryReadLock方法
// 尝试获取读锁,除了没有readerShouldBlock()外,其他基本一样
final boolean tryReadLock() {
// 当前线程
Thread current = Thread.currentThread()
for (;;) {
int c = getState(); // 获取锁状态数量
if (exclusiveCount(c) != 0 && // 独占锁不为空
getExclusiveOwnerThread() != current) // 且持有独占锁的线程不是当前线程,获取锁失败
return false;
int r = sharedCount(c); // 获取共享锁数量
// 锁数量来到最大值,抛出异常
if (r == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// 直接更新共享锁持有总数量
if (