ReentrantReadWriteLock可重入读写锁,它实现了ReadWriteLock接口,从而实现了读服务可以由多个线程进入,写线程只有一个线程可以进入。
ReentrantReadWriteLock中维护了一对锁,分别位一个读锁和一个写锁。通过读写分离提高了并发性。
- 同一时间内,可以允许多个线程访问。
- 写线程访问时,所有的读线程和写线程都会被阻塞。
注:本文以jdk 1.8源码阅读。
Sync类
和ReentrantLock一样,ReentrantReadWriteLock内部也有一个静态内部类Sync,其继承了AbstractQueuedSynchronizer类:源码如下:
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 6317671515068378041L;
/*
* Read vs write count extraction constants and functions.
* Lock state is logically divided into two unsigned shorts:
* The lower one representing the exclusive (writer) lock hold count,
* and the upper the shared (reader) hold count.
*/
// 高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;
/** 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; }
/**
* 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.
*/
//本地线程计数器类
static final class ThreadLocalHoldCounter
extends ThreadLocal<HoldCounter> {
public HoldCounter initialValue() {
return new HoldCounter();
}
}
/**
* The number of reentrant read locks held by current thread.
* Initialized only in constructor and readObject.
* Removed whenever a thread's read hold count drops to 0.
*/
// 本地线程计数器
private transient ThreadLocalHoldCounter readHolds;
/**
* The hold count of the last thread to successfully acquire
* readLock. This saves ThreadLocal lookup in the common case
* where the next thread to release is the last one to
* acquire. This is non-volatile since it is just used
* as a heuristic, and would be great for threads to cache.
*
* <p>Can outlive the Thread for which it is caching the read
* hold count, but avoids garbage retention by not retaining a
* reference to the Thread.
*
* <p>Accessed via a benign data race; relies on the memory
* model's final field and out-of-thin-air guarantees.
*/
// 缓存的计数器
private transient HoldCounter cachedHoldCounter;
/**
* firstReader is the first thread to have acquired the read lock.
* firstReaderHoldCount is firstReader's hold count.
*
* <p>More precisely, firstReader is the unique thread that last
* changed the shared count from 0 to 1, and has not released the
* read lock since then; null if there is no such thread.
*
* <p>Cannot cause garbage retention unless the thread terminated
* without relinquishing its read locks, since tryReleaseShared
* sets it to null.
*
* <p>Accessed via a benign data race; relies on the memory
* model's out-of-thin-air guarantees for references.
*
* <p>This allows tracking of read holds for uncontended read
* locks to be very cheap.
*/
// 第一个读线程
private transient Thread firstReader = null;
// 第一个读线程的计数
private transient int firstReaderHoldCount;
Sync() {
readHolds = new ThreadLocalHoldCounter();
setState(getState()); // ensures visibility of readHolds
}
/*
* Acquires and releases use the same code for fair and
* nonfair locks, but differ in whether/how they allow barging
* when queues are non-empty.
*/
/**
* Returns true if the current thread, when trying to acquire
* the read lock, and otherwise eligible to do so, should block
* because of policy for overtaking other waiting threads.
*/
abstract boolean readerShouldBlock();
/**
* Returns true if the current thread, when trying to acquire
* the write lock, and otherwise eligible to do so, should block
* because of policy for overtaking other waiting threads.
*/
abstract boolean writerShouldBlock();
/*
* Note that tryRelease and tryAcquire can be called by
* Conditions. So it is possible that their arguments contain
* both read and write holds that are all released during a
* condition wait and re-established in tryAcquire.
*/
//释放锁
protected final boolean tryRelease(int releases) {
//不是独占锁模式抛出异常
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
//减去release
int nextc = getState() - releases;
//如果独占锁持有数量为0 ,说明锁空闲,设置锁线程为null
boolean free = exclusiveCount(nextc) == 0;
if (free)
setExclusiveOwnerThread(null);
setState(nextc);
return free;
}
//获取锁
protected final boolean tryAcquire(int acquires) {
/*
* Walkthrough:
* 1. 如果读锁数量或者写锁非0,同时所有者不是一个线程,返回flase
* 1. If read count nonzero or write count nonzero
* and owner is a different thread, fail.
* 2.到达最大数量,返回flase
* 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;
}
//释放共享锁
protected final boolean tryReleaseShared(int unused) {
Thread current = Thread.currentThread();
//如果当前线程为第一个读线程并且读线程数量为1,设置firstReader为null,否这读线程数量 -1
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;
//如果总数小于等于1(只能为1),移除当前线程
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;
}
}
private IllegalMonitorStateException unmatchedUnlockException() {
return new IllegalMonitorStateException(
"attempt to unlock read lock, not locked by current thread");
}
//获取共享锁
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();
//判断写锁数量是否为0,如果不为0,且写锁线程不是当前线程,返回-1
//此处存在锁降级,当写锁数量不为0,但当前线程是写锁的线程,则写锁降级为读锁
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) {
//读锁为0,说明时第一个读线程
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
//第一个读线程为当前线程,firstReaderHoldCount计数器 + 1
firstReaderHoldCount++;
} else {
//不是第一个读线程,获取缓存计数器
HoldCounter rh = cachedHoldCounter;
//缓存计数器 + 1
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);
}
/**
* Full version of acquire for reads, that handles CAS misses
* and reentrant reads not dealt with in tryAcquireShared.
*/
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();
//写线程不为0并且不是当前线程,返回 -1
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) {
//当前线程是第一个读线程,第一个读线程计数器 + 1
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;
}
}
}
/**
* Performs tryLock for write, enabling barging in both modes.
* This is identical in effect to tryAcquire except for lack
* of calls to writerShouldBlock.
*/
//获取写锁
final boolean tryWriteLock() {
Thread current = Thread.currentThread();
int c = getState();
if (c != 0) {
//当前写锁数量
int w = exclusiveCount(c);
//写锁数量为0,或者持有锁线程不是当前线程
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;
}
/**
* Performs tryLock for read, enabling barging in both modes.
* This is identical in effect to tryAcquireShared except for
* lack of calls to readerShouldBlock.
*/
//获取读锁
final boolean tryReadLock() {
Thread current = Thread.currentThread();
for (;;) {
int c = getState();
//写锁线程不为0,且当前线程不是写锁线程
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;
}
}
}
//当前线程是否是独占锁线程
protected final boolean isHeldExclusively() {
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
// Methods relayed to outer class
final ConditionObject newCondition() {
return new ConditionObject();
}
final Thread getOwner() {
// Must read state before owner to ensure memory consistency
return ((exclusiveCount(getState()) == 0) ?
null :
getExclusiveOwnerThread());
}
//读锁数量
final int getReadLockCount() {
return sharedCount(getState());
}
//是否有写锁
final boolean isWriteLocked() {
return exclusiveCount(getState()) != 0;
}
//写锁数量
final int getWriteHoldCount() {
return isHeldExclusively() ? exclusiveCount(getState()) : 0;
}
//读锁数量
final int getReadHoldCount() {
if (getReadLockCount() == 0)
return 0;
Thread current = Thread.currentThread();
if (firstReader == current)
return firstReaderHoldCount;
HoldCounter rh = cachedHoldCounter;
if (rh != null && rh.tid == getThreadId(current))
return rh.count;
int count = readHolds.get().count;
if (count == 0) readHolds.remove();
return count;
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
readHolds = new ThreadLocalHoldCounter();
setState(0); // reset to unlocked state
}
final int getCount() { return getState(); }
}
Sync内部类的几个重要成员属性:
- SHARED_SHIFT // 高16位为读锁,低16位为写锁
- SHARED_UNIT // 读锁单位
- MAX_COUNT锁最大数量
- EXCLUSIVE_MASK写锁最大数量
- readHolds本地线程计数器
- cachedHoldCounter 缓存的计数器
- firstReader 第一个读线程
- firstReaderHoldCount 第一个读线程的计数器
尝试获取读锁通过TryReadLock方法,主要流程如下:
- 首先判断是否存在写线程,并判断当前线程是否是写线程,如果存在但写线程不是当前线程,获取锁失败,返回false;
- 获取读线程数量,如果到达最大数量抛出异常;
- 如果没有读线程,将当前线程设置为第一个读线程firstReader,并设置第一个读线程计数器 firstReaderHoldCount为1;
- 如果当前线程是第一个读线程,设置第一个读线程计数器firstReaderHoldCount + 1;
- 不是第一个读线程,刷新缓存计数器和本地线程计数器。
获取写锁通过tryWriteLock方法,主要流程如下:
- 获取线程状态数量,获取当前写锁线程数量,如果为0,或者当前线程不是写线程,获取失败,返回false;
- CAS尝试更新状态,更新成功之后设置当前线程为写锁线程。
NonFairSync类
//非公平锁的实现
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的apparentlyFirstQueuedIsExclusive方法用来判断当前锁是否已经被获取。此处代码如下:
final boolean apparentlyFirstQueuedIsExclusive() {
Node h, s;
return (h = head) != null &&
(s = h.next) != null &&
!s.isShared() && //非共享锁,即独占锁
s.thread != null;
}
FairSync类
//公平锁实现
static final class FairSync extends Sync {
private static final long serialVersionUID = -2274990926593161451L;
//使用AQS的hasQueuedPredecessors方法判断是否有前序节点,即自己不是首个等待获取同步状态的节点。
final boolean writerShouldBlock() {
return hasQueuedPredecessors();
}
final boolean readerShouldBlock() {
return hasQueuedPredecessors();
}
}
ReadLock类
public static class ReadLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -5992448646407690164L;
//内部实现
private final Sync sync;
//构造
protected ReadLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
//获取读锁,立即返回
public void lock() {
sync.acquireShared(1);
}
//获取读锁,响应中断
public void lockInterruptibly() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
//尝试获取读锁
public boolean tryLock() {
return sync.tryReadLock();
}
//带有超时获取锁
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
//释放锁
public void unlock() {
//调用AQS的方法
sync.releaseShared(1);
}
//Condition条件,读锁没有此实现。
public Condition newCondition() {
throw new UnsupportedOperationException();
}
public String toString() {
int r = sync.getReadLockCount();
return super.toString() +
"[Read locks = " + r + "]";
}
}
读锁的实际都是对Sync类实现的调用,读锁以公平锁还是非公平锁方式创建需要看外部传入的对象决定。
读锁获取的tryLock()方法不管是公平锁还是非公平锁方式,都是按照快速获取锁,即非公平锁方式获取锁的。如果要按照锁公平与否方式获取,使用tryLock(0, TimeUnit)方法。
WriteLock类
public static class WriteLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -4992448646407690164L;
private final Sync sync;
//构造
protected WriteLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
//加锁
public void lock() {
sync.acquire(1);
}
//加锁,响应中断
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
//尝试获取锁
public boolean tryLock( ) {
return sync.tryWriteLock();
}
//带有超时获取锁
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
//释放锁
public void unlock() {
sync.release(1);
}
//Condition条件
public Condition newCondition() {
return sync.newCondition();
}
public String toString() {
Thread o = sync.getOwner();
return super.toString() + ((o == null) ?
"[Unlocked]" :
"[Locked by thread " + o.getName() + "]");
}
//当前线程是否持有锁
public boolean isHeldByCurrentThread() {
return sync.isHeldExclusively();
}
//当前线程持有锁的数量
public int getHoldCount() {
return sync.getWriteHoldCount();
}
}
写锁和读锁都是对Sync类实现的调用,写锁以公平锁还是非公平锁方式创建需要看外部传入的对象决定。
ReentrantReadWriteLock类
以上介绍的都是ReentrantReadWriteLock类的内部实现类,实际上ReentrantReadWriteLock的实现都是基于以上内部类的实现。
//读锁
private final ReentrantReadWriteLock.ReadLock readerLock;
/** Inner class providing writelock */
//写锁
private final ReentrantReadWriteLock.WriteLock writerLock;
/** Performs all synchronization mechanics */
final Sync sync;
//默认创建非公平锁对象
public ReentrantReadWriteLock() {
this(false);
}
//创建读锁写锁和Sync对象,根据Fair字段决定创建公平锁还是非公平锁
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
//返回写锁对象
public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
//返回读锁对象
public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
//是否是公平锁
public final boolean isFair() {return sync instanceof FairSync; }
//写锁属于的线程
protected Thread getOwner() {
return sync.getOwner();
}
//读锁数量
public int getReadLockCount() {
return sync.getReadLockCount();
}
//是否是写锁
public boolean isWriteLocked() {
return sync.isWriteLocked();
}
//写锁是否被当前线程持有
public boolean isWriteLockedByCurrentThread() {
return sync.isHeldExclusively();
}
//写锁持有数量
public int getWriteHoldCount() {
return sync.getWriteHoldCount();
}
//读锁持有数量
public int getReadHoldCount() {
return sync.getReadHoldCount();
}
//写锁等待集合
protected Collection<Thread> getQueuedWriterThreads() {
return sync.getExclusiveQueuedThreads();
}
//读锁等待集合
protected Collection<Thread> getQueuedReaderThreads() {
return sync.getSharedQueuedThreads();
}
//CLH中是否有等待线程
public final boolean hasQueuedThreads() {
return sync.hasQueuedThreads();
}
//当前线程是否在CLH队列中
public final boolean hasQueuedThread(Thread thread) {
return sync.isQueued(thread);
}
//CLH长度
public final int getQueueLength() {
return sync.getQueueLength();
}
//CLH队列中所有等待线程的集合
protected Collection<Thread> getQueuedThreads() {
return sync.getQueuedThreads();
}
//是否有Condition等待条件
public boolean hasWaiters(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
}
读写锁内部维护的锁其实只有一个Sync,只是在获取读锁 和写锁的方式不同。Sync的实现实际上就是基于AQS的实现,分为公平锁和非公平锁实现,上文已列出源码。
锁降级
在Sync类的tryAcquiredShared方法和fullTryAcquiredShared两个方法中,有存在锁降级的地方,具体代码如下:
//写线程不为0并且不是当前线程,返回 -1
//此处存在锁降级,当写锁数量不为0,但当前线程是写锁的线程,则写锁降级为读锁
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)
return -1;
// else we hold the exclusive lock; blocking here
// would cause deadlock.
}
当前线程为持有写锁的线程的时候,写锁降级为读锁。对于锁降级的情况下,读锁获取的锁也必须要释放。如果没有释放读锁而只释放了写锁,会导致其他线程在获取写锁时发现还有读锁线程没有释放读锁,从而导致阻塞。
参考资料
【死磕 Java 并发】—– J.U.C 之读写锁:ReentrantReadWriteLock