在Java的锁中很多锁都是同一时刻只允许一个线程访问,今天就来看看一个特殊的锁——读写锁。它的特殊之处就在于同一时刻可以运行多个读线程访问或者有一个写线程在访问。能够大大的提高并发性和吞吐量
读写锁是一种特殊的自旋锁。在读写锁的世界里,访问共享资源的线程被划分为两类:一类是只对共享资源进行访问而不更改,暂且认为他是读者;一类是改变共享资源,即写操作,是写者。这个锁的核心要求是在没有任何线程获得读锁和写锁的情况才能获得写锁。
公平性:读写锁支持非公平和公平的锁获取方式,非公平锁的吞吐量优于公平锁的吞吐量,默认构造的是非公平锁
可重入:在线程获取读锁之后能够再次获取读锁,但是不能获取写锁,而线程在获取写锁之后能够再次获取写锁,同时也能获取读锁
锁降级:线程获取写锁之后获取读锁,再释放写锁,这样实现了写锁变为读锁,也叫锁降级
1、类的属性
abstract static class Sync extends AbstractQueuedSynchronizer {
// 版本序列号
private static final long serialVersionUID = 6317671515068378041L;
// 通过将整形变量state切成两部分,高16位表示读,低16位表示写,来区分读写状态。
static final int SHARED_SHIFT = 16;
static final int SHARED\_UNIT = (1 << SHARED\_SHIFT);
static final int MAX\_COUNT = (1 << SHARED\_SHIFT) - 1;
static final int EXCLUSIVE\_MASK = (1 << SHARED\_SHIFT) - 1;
// 本地线程计数器
private transient ThreadLocalHoldCounter readHolds;
// 缓存的计数器
private transient HoldCounter cachedHoldCounter;
// 第一个读线程
private transient Thread firstReader = null;
// 第一个读线程的计数
private transient int firstReaderHoldCount;
}
在ReentrantReadWriteLock中,读写状态的区分是其同步容器Sync的同步状态。而在Sync中应该有读线程的两种和写线程的两种状态。但是通常整形变量只能表示两种状态,这里需要四种所以就将整形变量分成高16位和低16位
上图的同步状态表示一个线程已经获取了写锁,且重进入了两次,同时也连续获取了两次读锁。这个状态如何快速获取呢?
static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
上面这个方法能快速获得读状态,通过当前状态的无符号补0右移,能够将高16的状态移到低16位从而得到正常的数值状态。
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
上面这个方法则是快速获取写状态,直接将高16位抹去(相当于c&0x0000FFFF)
2、写锁的释放和获取
protected final boolean tryRelease(int releases) {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
int nextc = getState() - releases;
boolean free = exclusiveCount(nextc) == 0;
if (free)
setExclusiveOwnerThread(null);
setState(nextc);
return free;
}
tryRelease:先判断是否拿到的是独占的资源,不是就表示可能线程拿的是读锁或者没有锁,这时候直接抛异常。如果是写锁那么就判断释放的锁的个数是否是当前锁的数量,是就释放所有写锁并且设置状态,否则就只设置状态。
protected final boolean tryAcquire(int acquires) {
/*
* Walkthrough:
* 1. If read count nonzero or write count nonzero
* and owner is a different thread, fail.
* 2. If count would saturate, fail. (This can only
* happen if count is already nonzero.)
* 3. Otherwise, this thread is eligible for lock if
* it is either a reentrant acquire or
* queue policy allows it. If so, update state
* and set owner.
*/
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;
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;
setExclusiveOwnerThread(current);
return true;
}
tryAcquire:首先这个方法会先获取state和线程的写锁个数,如果当前线程拿到了锁那么就判断拿的是否是写锁,如果ReentrantReadWriteLock存在读锁或者当先线程不是获取写锁的线程(即不是获取独占资源的线程),那么直接返回false,否则,根据可重入原则是可以获取锁的。或者另外一种情况就是当前线程没有拿到锁,然后在公平和非公平的情况下判断当前线程是否该被阻塞(公平情况下是看队列头部的直接后继,非公平就竞争),如果线程不该被阻塞就可以获取到锁。这时候获取的是写锁。
3、读锁的释放和获取
protected final boolean tryReleaseShared(int unused) {
Thread current = Thread.currentThread();
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
if (firstReaderHoldCount == 1)
firstReader = null;
else
firstReaderHoldCount--;
} 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;
}
}
tryReleaseShared:主要是表示读锁线程释放锁。如果当前线程是第一个读线程且占有资源数firstReaderHoldCount为1,则可以直接释放该读线程,否则就firstReaderHoldCount减1。如果当前线程不是第一个读线程就会拿缓存计数器,用缓存计数器判断当前线程是否被缓存了或者是否是当前线程。如果计数器的值在缓存中,并且是当前的线程,那么就获取计数器中的计数count,否则还需要获取当前线程的计数器。获取完计数count之后计数值小于等于1就直接移除当前线程的计数器,而后count小于等于0就抛异常,否则就减少计数即可。之后就会进入无限循环,循环能够确保成功设置state。上述函数就是释放读锁,只不过对于当前线程是否是第一个读线程分两种情况来释放,最终能够获得state。
protected final int tryAcquireShared(int unused) {
/*
* Walkthrough:
* 1. If write lock held by another thread, fail.
* 2. Otherwise, this thread is eligible for
* lock wrt state, so ask if it should block
* because of queue policy. If not, try
* to grant by CASing state and updating count.
* Note that step does not check for reentrant
* acquires, which is postponed to full version
* to avoid having to check hold count in
* the more typical non-reentrant case.
* 3. If step 2 fails either because thread
* apparently not eligible or CAS fails or count
* saturated, chain to version with full retry loop.
*/
Thread current = Thread.currentThread();
int c = getState();
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
return -1;
int r = sharedCount(c);
if (!readerShouldBlock() &&
r < MAX_COUNT &&
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 1;
}
return fullTryAcquireShared(current);
}
tryAcquireShared:获取读锁。首先就是当前线程为写线程或是独占锁的线程那么就会直接返回-1,当前线程不是写线程也不是独占的线程就获取ReentrantReadWriteLock的读锁数量判断读线程不应该被阻塞(分公平和不公平)并且小于读锁数量的最大值,并且设置状态成功。如果当前没有线程获取读锁,则这个线程就是第一个读线程,并且设置第一个读线程firstReader和firstReaderHoldCount;。如果当前线程为第一个读线程,只需要增加firstReaderHoldCount。上述两种情况不满足就设置当前线程对应的计数器HoldCounter。
final int fullTryAcquireShared(Thread current) {
/*
* This code is in part redundant with that in
* tryAcquireShared but is simpler overall by not
* complicating tryAcquireShared with interactions between
* retries and lazily reading hold counts.
*/
HoldCounter rh = null;
for (;;) {
int c = getState();
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)
return -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;
}
}
}
fullTryAcquireShared:如果读线程被阻塞或者大于最大值,或者比较设置没成功。那么就会无限循环tryAcquireShared使得线程一定能获取读锁,如果是大于最大值则会抛异常。过程与tryAcquireShared类似。
4、直接竞争锁
final boolean tryWriteLock() {
Thread current = Thread.currentThread();
int c = getState();
if (c != 0) {
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))
return false;
setExclusiveOwnerThread(current);
return true;
}
tryWriteLock:实现机制与tryAcquire类似,但是区别在于不会去检查是否该线程获取写锁是否会被阻塞,直接让线程尝试竞争锁。
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;
}
}
}
tryReadLock:与实现机制tryAcquireShared,同样是直接让线程去竞争读锁
再提醒一下就是读写锁的核心要求是在没有任何线程获得读锁和写锁的情况才能获得写锁。可以实现锁的降级(当前线程拥有写锁且还没释放的情况拿到读锁,再释放写锁,实现了写锁到读锁的转换),但无法实现锁的升级,同样支持可重入和公平锁与非公平锁。相比于ReentrantLock提高了线程访问资源的吞吐量。
手机扫一扫
移动阅读更方便
你可能感兴趣的文章