1.首先看類的定義:
abstract static class Sync extends AbstractQueuedSynchronizer
Sync是抽象類,且繼承了AbstractQueuedSynchronizer而AbstractQueuedSynchronizer繼承了AbstractOwnableSynchronizer
其中AbstractOwnableSynchronizer定義了一個獨佔線程,並提供了GET、SET方法。
private transient Thread exclusiveOwnerThread;
AbstractQueuedSynchronizer抽象類提供了一個基於FIFO隊列,可以用於構建鎖或者其他相關同步裝置的基礎框架,具體源碼另寫博客分享。
2.定義了幾個常量和變量
static final int SHARED_SHIFT = 16; AQS的state字段拆成兩部分了,高16位表示讀鎖的次數,低16位表示寫鎖的次數
static final int SHARED_UNIT = (1 << SHARED_SHIFT);每次線程獲取讀鎖成功就會執行state+=SHARED_UNIT操作,不是+1因爲高16位表示獲取讀鎖的次數。
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;允許讀或寫獲取鎖的最大次數,都是65535
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
/** Returns the number of shared holds represented in count */獲取當前讀鎖的總數
static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
/** Returns the number of exclusive holds represented in count */獲取當前寫鎖的總數
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
private transient ThreadLocalHoldCounter readHolds;當前線程擁有的讀鎖的個數
private transient HoldCounter cachedHoldCounter;成功獲取讀鎖的最後一個線程的HoldCounter
private transient Thread firstReader = null;第一個獲取到讀鎖的線程
private transient int firstReaderHoldCount; firstReader線程的HoldCounter
/**
* A counter for per-thread read hold counts.
* Maintained as a ThreadLocal; cached in cachedHoldCounter
*/
static final class HoldCounter {
int count = 0;
// Use id, not reference, to avoid garbage retention
final long tid = getThreadId(Thread.currentThread());
}
/**
* ThreadLocal subclass. Easiest to explicitly define for sake
* of deserialization mechanics.每個線程都綁定一個HoldCounter
*/
static final class ThreadLocalHoldCounter
extends ThreadLocal<HoldCounter> {
public HoldCounter initialValue() {
return new HoldCounter();
}
}
3.構造函數
Sync() {
readHolds = new ThreadLocalHoldCounter();初始化readHolds
setState(getState()); // ensures visibility of readHolds
}
4.tryAcquire方法
1.如果有讀線程和寫線程且非當前線程,則失敗,2.如果計數飽和,則失敗,3.否則,這個線程可以擁有鎖,隊列策略允許或者可重入的鎖,更新狀態並設置所有者
protected final boolean tryAcquire(int acquires) {
Thread current = Thread.currentThread();
int c = getState();
int w = exclusiveCount(c);
if (c != 0) {
// (Note: if c != 0 and w == 0 then shared count != 0)
if (w == 0 || current != getExclusiveOwnerThread())
return false;//如果c!=0且w==0,說明有讀鎖,返回false,如果c!=0且w!=0且非當前線程,則返回false
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");//寫鎖數量超過最大,則報錯
// Reentrant acquire
setState(c + acquires);//設置狀態
return true;
}
if (writerShouldBlock() ||
!compareAndSetState(c, c + acquires))
return false;//如果寫阻塞或者CAS失敗,則返回false
setExclusiveOwnerThread(current);//設置獨佔線程標識
return true;
}
5.tryRelease方法
protected final boolean tryRelease(int releases) {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();//如果獨佔線程非當前線程,拋異常
int nextc = getState() - releases;
boolean free = exclusiveCount(nextc) == 0;
if (free)
setExclusiveOwnerThread(null);//釋放鎖後設置獨佔線程爲null
setState(nextc);//設置狀態
return free;
}
6.tryAcquireShared方法
protected final int tryAcquireShared(int unused) {
/*
* Walkthrough:
* 1. 如果寫鎖被另一個線程持有,則返回失敗
* 2. 否則,繼續判斷,如果隊列策略允許(readerShouldBlock返回false)獲取鎖且CAS設置state成功,則設置讀鎖count的值。這一步並沒有檢查讀鎖重入的情況,被延遲到fullTryAcquireShared裏了,因爲大多數情況下不是重入的;
* 3. 如果步驟2失敗了,或許是隊列策略返回false或許是CAS設置失敗了等,則執行fullTryAcquireShared
*/
Thread current = Thread.currentThread();
int c = getState();
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
return -1;//如果有線程持有寫鎖,且非當前線程,則返回-1
int r = sharedCount(c);
if (!readerShouldBlock() &&
r < MAX_COUNT &&
compareAndSetState(c, c + SHARED_UNIT)) {//如果隊列策略允許且讀鎖不超過最大值且CAS狀態成功
if (r == 0) {//如果讀鎖個數爲0,則設置線程和線程持有的鎖個數
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {//否則,如果讀鎖非0,且爲當前線程,則增加線程持有個數
firstReaderHoldCount++;
} else {//否則,讀鎖非0,且非當前線程
HoldCounter rh = cachedHoldCounter;//最後一個獲取到讀鎖的持有個數
if (rh == null || rh.tid != getThreadId(current))
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
}
return 1;
}
return fullTryAcquireShared(current);
}
final int fullTryAcquireShared(Thread current) {
HoldCounter rh = null;
for (;;) {
int c = getState();
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)
return -1;//如果寫鎖個數不爲空且非當前線程,則返回-1
// else we hold the exclusive lock; blocking here
// would cause deadlock.
} else if (readerShouldBlock()) {
// Make sure we're not acquiring read lock reentrantly
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
} else {
if (rh == null) {
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current)) {
rh = readHolds.get();
if (rh.count == 0)
readHolds.remove();
}
}
if (rh.count == 0)
return -1;
}
}
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
if (compareAndSetState(c, c + SHARED_UNIT)) {
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)
readHolds.set(rh);
rh.count++;
cachedHoldCounter = rh; // cache for release
}
return 1;
}
}
}
7.tryReleaseShared方法
protected final boolean tryReleaseShared(int unused) {
Thread current = Thread.currentThread();
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
if (firstReaderHoldCount == 1)
firstReader = null;//如果當前線程擁有一個讀鎖,則設置firstReader爲null
else
firstReaderHoldCount--;//否則,鎖個數減1
} else {
HoldCounter rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
rh = readHolds.get();
int count = rh.count;
if (count <= 1) {
readHolds.remove();
if (count <= 0)
throw unmatchedUnlockException();
}
--rh.count;
}
for (;;) {
int c = getState();
int nextc = c - SHARED_UNIT;
if (compareAndSetState(c, nextc))
// Releasing the read lock has no effect on readers,
// but it may allow waiting writers to proceed if
// both read and write locks are now free.
return nextc == 0;
}
}
8.tryWriteLock
final boolean tryWriteLock() {
Thread current = Thread.currentThread();
int c = getState();
if (c != 0) {//如果c!=0且w==0則表示讀鎖不爲空,返回false,或者寫鎖不爲空且非當前線程,則返回false
int w = exclusiveCount(c);
if (w == 0 || current != getExclusiveOwnerThread())
return false;
if (w == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
}
if (!compareAndSetState(c, c + 1))//CAS失敗,返回false
return false;
setExclusiveOwnerThread(current);//設置線程
return true;
}
9.tryReadLock
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 (compareAndSetState(c, c + SHARED_UNIT)) {
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)
readHolds.set(rh);
rh.count++;
}
return true;
}
}
}
10.非公平版本
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -8159625535654395037L;
final boolean writerShouldBlock() {//寫線程可以插隊
return false; // writers can always barge
}
final boolean readerShouldBlock() {
/* As a heuristic to avoid indefinite writer starvation,
* block if the thread that momentarily appears to be head
* of queue, if one exists, is a waiting writer. This is
* only a probabilistic effect since a new reader will not
* block if there is a waiting writer behind other enabled
* readers that have not yet drained from the queue.
*/
return apparentlyFirstQueuedIsExclusive();//爲了防止寫線程飢餓,如果AQS等待隊裏的第一個線程是獨佔的,則讀線程阻塞
}
}
11.公平版本
/**
* Fair version of Sync
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -2274990926593161451L;
final boolean writerShouldBlock() {
return hasQueuedPredecessors();//如果AQS有等待的線程,則當前線程阻塞
}
final boolean readerShouldBlock() {
return hasQueuedPredecessors();
}
}