引言
上一篇文章,我们学习了ReentrantLock和AQS,ReentrantLock能够实现排他重入锁的逻辑。排他锁意味着任意时刻只有一个线程能够获取锁。但是在读多写少的场景下,排他锁的性能可能不太理想,因为一个读线程也会阻塞其他的读线程和写线程,而数据的读取实际上是不需要对其他读线程加锁的。这篇文章,我们来看juc中提供的读写锁ReentrantReadWriteLock。
类的体系结构
ReetrantReadWriteLock类是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 class ReentrantReadWriteLock
implements ReadWriteLock, java.io.Serializable {
private static final long serialVersionUID = -6992448646407690164L;
/** Inner class providing readlock */
private final ReentrantReadWriteLock.ReadLock readerLock;
/** Inner class providing writelock */
private final ReentrantReadWriteLock.WriteLock writerLock;
/** Performs all synchronization mechanics */
final Sync sync;
其中ReadLock和WriteLock都是ReentrantReadWriteLock的内部类,它俩都实现了lock接口:
public static class ReadLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -5992448646407690164L;
private final Sync sync;
}
public static class WriteLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -4992448646407690164L;
private final Sync sync;
}
读锁和写锁也分别有一个同步器。
同步器Sync与ReentrantLock中的Sync一样,都继承了AbstractQueuedSynchronizer:
abstract static class Sync extends AbstractQueuedSynchronizer {
并且ReentrantReadWriteLock也提供了同步器的非公平版本和公平版本,分别是NonfairSync和FairSync。
static final class FairSync extends Sync {}
static final class NonfairSync extends Sync {}
读写锁和同步器的初始化
从类的体系结构我们可以看出,ReentrantReadWriteLock有两个锁,一个读锁一个写锁,还有一个同步器,那么它是怎么实例化的呢?我们来看它的构造方法:
/**
* Creates a new {@code ReentrantReadWriteLock} with
* default (nonfair) ordering properties.
*/
public ReentrantReadWriteLock() {
this(false);
}
/**
* Creates a new {@code ReentrantReadWriteLock} with
* the given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
它有两个构造方法,但都是通过第二个来实现的。传入的参数指定是公平锁还是非公平锁,公平锁和非公平锁对应的同步器分别是FairSync和NonFairSync。然后会使用这个同步器来初始化读锁和写锁,下面两个是读锁和写锁的构造方法:
protected ReadLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
protected WriteLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
也就是,读锁和写锁的同步器就是ReetrantReadWriteLock的同步器。
由于ReetrantReadWriteLock的读锁和写锁是分离的,所以ReetrantReadWriteLock本身不会提供lock和unlock这类的方法,加锁和解锁都是分别由ReadLock和WriteLock提供的。下面我们分别分析这两种锁的加锁和解锁。
读锁的加锁和解锁
加锁
读锁的加锁调用的是同步器的acquireShared方法:
public void lock() {
sync.acquireShared(1);
}
该方法是AQS提供的:
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
它首先调用的是tryAcquireShared方法:
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并且同步器的所有者线程不是当前线程
//意味着有其他线程正在进行写操作 返回-1
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,也就是没有取到读锁,会执行doAcquireShared方法:
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
这个方法是将线程构造成Node并加入等待队列,然后不断的自旋中去继续获取锁。与上一篇文章的独占锁的获取类似,如果没有获取到锁,当前线程会将自己挂起,等待其他线程唤醒或者中断。
解锁
读锁的释放需要调用readLock的unlock方法,unlock方法调用的是releaseShared方法:
public void unlock() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
来看tryReleaseShared方法:
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;
}
}
读锁的每次释放都会减少读锁被持有的次数,减少的值是1<<16。
写锁的加锁和解锁
加锁
写锁的加锁调用的是WriterLock的lock方法:
public void lock() {
sync.acquire(1);
}
acquire方法是AQS提供的:
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
首先会调用tryAcquire来获取锁,tryAcquire是Sync给出的:
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) {
//锁状态不为0 也就是读锁或者写锁被持有
// (Note: if c != 0 and w == 0 then shared count != 0)
//如果写锁被持有的次数是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没有成功,调用的是acquireQueued(addWaiter(Node.EXCLUSIVE), arg)方法,这个方法与前面讲到的ReentrantLock中独占锁的获取逻辑是一样的,这里不再赘述。
解锁
写锁的解锁调用的是writeLock的unlock方法:
public void unlock() {
sync.release(1);
}
unlock调用的是release方法:
public final boolean release(int arg) {
if (tryRelease(arg)) {
Node h = head;
if (h != null && h.waitStatus != 0)
unparkSuccessor(h);
return true;
}
return false;
}
tryRelease方法是Sync提供的:
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;
}
首先判断锁是否被当前线程持有。之后的逻辑就是减少写锁被重入的数量,如果写锁被当前线程持有并且没有重入,那么写锁的数量就会是零,也就是锁会被释放,否则,将锁被持有的数量减1,锁仍然被当前线程持有。