这篇文章主要记录下ReadWriteLock的实现原理与用处,ReentrantLock可以实现线程安全,但是它的锁粒度太大,和Synchronized一样要么获取锁要么阻塞,与数据库共享锁与排他锁的思想类似,其实读操作与读操作是不用互相阻塞的,读写锁就是解决这个问题。
1、 ReadWriteLock
ReadWriteLock的定义如下,从定义可以看出实现了读写锁的分离:
public interface ReadWriteLock {
/**
* Returns the lock used for reading.
*
* @return the lock used for reading
*/
Lock readLock();
/**
* Returns the lock used for writing.
*
* @return the lock used for writing
*/
Lock writeLock();
}
我们一般使用是它的实现类ReentrantReadWriteLock:
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
2、AQS
Java的很多同步机制像ReentrantLock、Semphore、CountDownLatch等等都是使用AQS(AbstractQueuedSynchronizer)实现的,AQS抽象类提供了同步实现的框架,它的核心在于state、tryAcquire、tryRelease三个域属性,通过state来保存信号量/锁的状态或者个数,然后获取与释放的tryAcquire、tryRelease操作就是通过对state状态的修改来实现的。
3、ReentrantReadWriteLock
ReentrantReadWriteLock中的sync实现了AQS类并定义了自己的acquire、release方法。当我们调用readerLock.lock/unlock时就是调用的sync的tryAcquireShared与tryReleaseShared方法,同样writerLock.lock/unlock调用的是tryAcquire与tryRelease方法。先看看ReentrantReadWriteLock中AQS的变量的定义:
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.
*/
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; // initially 0
// Use id, not reference, to avoid garbage retention
final long tid = LockSupport.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.*/
private transient ThreadLocalHoldCounter readHolds;
/**
* The hold count of the last thread to successfully acquire
* readLock. */
private transient HoldCounter cachedHoldCounter;
private transient Thread firstReader;
private transient int firstReaderHoldCount;
这里只列出了重要的部分,之前说AQS的一个重点在于state,在ReentrantReadWriteLock中由于有读锁和写锁,但是只有一个state值,因为state是一个int值,所以这里的实现是高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. */ //这个c就是state值
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; }
有了上面的基础,就可以看读写锁获取与释放锁的具体实现了,先看readLock的acquire方法:
@ReservedStackAccess
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(); //获取state值
if (exclusiveCount(c) != 0 && //如果有写锁,并且持有写锁的不是当前线程,则获取读锁失败
getExclusiveOwnerThread() != current)
return -1;
int r = sharedCount(c); //当前读锁的数量
if (!readerShouldBlock() &&
r < MAX_COUNT &&
compareAndSetState(c, c + SHARED_UNIT)) { //通过CAS来更新state(读锁数量+1)
if (r == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
firstReaderHoldCount++;
} else {
//这里注意因为锁是可重入的,cachedHoldCounter记录了最后1个获取读锁的线程的重入次数。
//firstReaderHoldCounter记录了第一个获取读锁的线程的重入次数
//对读锁进行计数时需要对每个线程持有的读锁分别计数。
//HoldCounter 是一个ThreadLocal对象,使用它来记录线程持有的读锁数量
HoldCounter rh = cachedHoldCounter;
if (rh == null ||
rh.tid != LockSupport.getThreadId(current))
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
}
return 1;
}
return fullTryAcquireShared(current);
}
再看看readLock的release方法,获取锁的时候计数增加,释放锁自然是计数减少:
@ReservedStackAccess
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 != LockSupport.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;
}
}
对于writeLock,因为写锁是排他的,所以更改状态(写锁数量)就行了,因为锁的可重入性,所以状态值也可能是任意值:
/*
* 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.
*/
@ReservedStackAccess
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;
}
@ReservedStackAccess
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)
// // c!=0,w==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;
}
}
4、其他
除了上面的基础讲解,ReentrantReadWriteLock还有一些其他的特性:
1、公平锁与非公平锁(公平模式下锁的申请都必须按照AQS锁等待队列先进先出,非公平下可插队)
2、如果1个线程获得了读锁,那么它不能同时再获得写锁,这个就是所谓的“锁升级”,读锁升级到写锁可能会造成死锁,所以是不允许的;如果1个线程获得了写锁,那么不允许其他线程再获得读锁和写锁,但是它自己可以获得读锁,就是所谓的“锁降级”