一:简介

ReentrantReadWriteLock,读写锁,是对ReentrankLock的改进,通过对读锁与写锁的分离,达到提高性能的目的。比如:在一些业务场景中,大部分只是读数据,写数据很少,如果仅仅是读数据的话并不会影响数据正确性(出现脏读),而如果在这种业务场景下,依然使用独占锁的话,很显然这将是出现性能瓶颈的地方,这个时候就需要用到读写锁了。
读写锁,分为读锁与写锁,因为仅拿读取操作来说不存在线程安全问题,所以同一个时刻可以有多个线程持有读锁,但是因为写操作会改变数据,所以在写线程访问时,所有的持有读锁的线程与其他的写线程都应该阻塞, 即遵循读写互斥,写写互斥原则。
在读写锁中,其特性为以下三个方面:
1:公平性选择,支持非公平(默认)和公平原则
2 : 重进入,该锁支持重进入,在读线程获取读锁后,能再次获取读锁。同样,写线程在获取写锁后也能再次获取写锁。
3:锁降级原则:遵循获取写锁、获取读锁再释放写锁的次序,写锁可以被降级为读锁。

下面就就来具体分析:

二:写锁分析:

2.1写锁的获取

  1. public static class WriteLock implements Lock, java.io.Serializable {
  2. ...........
  3. public void lock() {
  4. sync.acquire(1);
  5. }
  6. .........
  7. }

可以发现,仍然是AQS中的模板方法,所以直接分析Sync中的tryAcquire:

  1. protected final boolean tryAcquire(int acquires) {
  2. /*
  3. * Walkthrough:
  4. * 1. If read count nonzero or write count nonzero
  5. * and owner is a different thread, fail.
  6. * 2. If count would saturate, fail. (This can only
  7. * happen if count is already nonzero.)
  8. * 3. Otherwise, this thread is eligible for lock if
  9. * it is either a reentrant acquire or
  10. * queue policy allows it. If so, update state
  11. * and set owner.
  12. */
  13. Thread current = Thread.currentThread();
  14. int c = getState(); //获取写锁当前的状态state
  15. int w = exclusiveCount(c); //获取写锁获取的次数
  16. if (c != 0) {
  17. // (Note: if c != 0 and w == 0 then shared count != 0)
  18. //当读锁已经被读线程获取 或者 当前线程不是获取写锁的线程
  19. //当前线程获取写锁失败
  20. if (w == 0 || current != getExclusiveOwnerThread())
  21. return false;
  22. if (w + exclusiveCount(acquires) > MAX_COUNT)
  23. throw new Error("Maximum lock count exceeded");
  24. // Reentrant acquire
  25. //当前线程获取写锁,支持可重复加锁
  26. setState(c + acquires);
  27. return true;
  28. }
  29. //这个方法是公平与非公平锁的获取判断
  30. if (writerShouldBlock() ||
  31. !compareAndSetState(c, c + acquires)) //非公平可直接利用CAS获取锁
  32. return false;
  33. //写锁未被任何线程获取,当前线程可获取写锁
  34. setExclusiveOwnerThread(current);
  35. return true;
  36. }

这段代码的逻辑需要关注几个点;
(1)exclusiveCount(..),其源码为:

  1. /** Returns the number of exclusive holds represented in count */
  2. static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
  3. // EXCLUSIVE _MASK为1左移16位然后减1,即为0x0000FFFF。
  4. static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

而exclusiveCount方法是将同步状态(state为int类型)与0x0000FFFF相与,即取同步状态的低16位。那么低16位代表什么呢?根据exclusiveCount方法的注释为独占式获取的次数即在这里是写锁被获取的次数,现在就可以得出来一个结论同步状态的低16位用来表示写锁的获取次数。
(2)同时还需要注意一个方法:

  1. /** Returns the number of shared holds represented in count */
  2. static int sharedCount(int c) { return c >>> SHARED_SHIFT; }

该方法是获取读锁被获取的次数,是将同步状态(int c)右移16次,即取同步状态的高16位,现在我们可以得出另外一个结论同步状态的高16位用来表示读锁被获取的次数。
即读写锁的读锁和写锁分别记录状态的方式就是state的高十六位(记录读锁状态),低十六位(记录写锁的状态)。

(3)还有一个公平与非公平的判断:
在读写锁中,

  1. static final class FairSync extends Sync {
  2. private static final long serialVersionUID = -2274990926593161451L;
  3. final boolean writerShouldBlock() {
  4. return hasQueuedPredecessors();
  5. }
  6. final boolean readerShouldBlock() {
  7. return hasQueuedPredecessors();
  8. }
  9. }
  10. static final class NonfairSync extends Sync {
  11. private static final long serialVersionUID = -8159625535654395037L;
  12. final boolean writerShouldBlock() {
  13. return false; // writers can always barge
  14. }
  15. final boolean readerShouldBlock() {
  16. return apparentlyFirstQueuedIsExclusive();
  17. }
  18. }

这里是通过了两个方法即读和写应不应该阻塞的方法的返回值作为公平与非公平的区分,,在上面的tryAcquire(..)中:

  1. //这个方法是公平与非公平锁的获取判断
  2. if (writerShouldBlock() ||
  3. !compareAndSetState(c, c + acquires)) //非公平可直接利用CAS获取锁
  4. return false;

可以看到,非公平还是可直利用CAS获取锁。

现在,总结一下写锁获取方法tryACquire(),其主要的逻辑为,当读锁已经被线程获取或者写锁已经被其他线程获取时,则写锁获取失败(因为读写锁要遵循获取写锁,获取读锁再释放写锁的次序),否则,获取成功并支持重入,增加写状态state中的低16位。
2.2:写锁的释放:
同理,也是通过重写tryRelease方法后,通过调用模板方法release实现的:

  1. protected final boolean tryRelease(int releases) {
  2. if (!isHeldExclusively())
  3. throw new IllegalMonitorStateException();
  4. //同步状态减去写状态
  5. int nextc = getState() - releases;
  6. //判断写状态(即nextc的低十六位)是否清空为0,为0时释放锁
  7. boolean free = exclusiveCount(nextc) == 0;
  8. if (free)
  9. setExclusiveOwnerThread(null);
  10. setState(nextc); //更新state
  11. return free;
  12. }

释放锁的逻辑与ReentrankLock的所释放基本相同,需要注意的是,写状态是用state的低16为保存的,所以在判断free时是在判断nextc的低十六位是否为0.

3:读锁的详情:
因为多个线程均可同时持有读锁,所以读锁不是独占锁,而是共享锁,所以需要重写AQS中的tryAcquireShared方法和tryReleaseShared方法:

  1. protected final int tryAcquireShared(int unused) {
  2. /*
  3. * Walkthrough:
  4. * 1. If write lock held by another thread, fail.
  5. * 2. Otherwise, this thread is eligible for
  6. * lock wrt state, so ask if it should block
  7. * because of queue policy. If not, try
  8. * to grant by CASing state and updating count.
  9. * Note that step does not check for reentrant
  10. * acquires, which is postponed to full version
  11. * to avoid having to check hold count in
  12. * the more typical non-reentrant case.
  13. * 3. If step 2 fails either because thread
  14. * apparently not eligible or CAS fails or count
  15. * saturated, chain to version with full retry loop.
  16. */
  17. Thread current = Thread.currentThread();
  18. int c = getState(); //获取同步状态
  19. //1. 如果写锁已经被获取并且获取写锁的线程不是当前线程的话,当前
  20. // 线程获取读锁失败返回-1
  21. if (exclusiveCount(c) != 0 &&
  22. getExclusiveOwnerThread() != current)
  23. return -1;
  24. int r = sharedCount(c); //从同步状态中获取共享的次数,上面已经分析过了,state的高16位
  25. if (!readerShouldBlock() &&
  26. r < MAX_COUNT && //2:当前线程获取读锁
  27. compareAndSetState(c, c + SHARED_UNIT)) { //更新state的状态
  28. //3. 下面的代码主要是新增的一些功能,比如getReadHoldCount()方法
  29. //返回当前获取读锁的次数
  30. if (r == 0) {
  31. firstReader = current;
  32. firstReaderHoldCount = 1;
  33. } else if (firstReader == current) {
  34. firstReaderHoldCount++;
  35. } else {
  36. HoldCounter rh = cachedHoldCounter;
  37. if (rh == null || rh.tid != getThreadId(current))
  38. cachedHoldCounter = rh = readHolds.get();
  39. else if (rh.count == 0)
  40. readHolds.set(rh);
  41. rh.count++;
  42. }
  43. return 1;
  44. }
  45. //4. 处理在第二步中CAS操作失败的自旋已经实现读锁的重入性
  46. return fullTryAcquireShared(current);
  47. }

从代码逻辑中可以看出,当写锁被其他线程获取了就获取读锁失败了(必须遵循获取写锁,获取读锁,释放写锁的原则),否则获取成功后利用CAS更新同步状态。如果CAS失败或者已经获取读锁的线程再次获取读锁时,是靠fullTryAcquireShared方法实现的,具体代码就不贴了,感兴趣了可以看看。

3.2:读锁的释放

  1. protected final boolean tryReleaseShared(int unused) {
  2. Thread current = Thread.currentThread();
  3. // 前面还是为了实现getReadHoldCount等新功能
  4. if (firstReader == current) {
  5. // assert firstReaderHoldCount > 0;
  6. if (firstReaderHoldCount == 1)
  7. firstReader = null;
  8. else
  9. firstReaderHoldCount--;
  10. } else {
  11. HoldCounter rh = cachedHoldCounter;
  12. if (rh == null || rh.tid != getThreadId(current))
  13. rh = readHolds.get();
  14. int count = rh.count;
  15. if (count <= 1) {
  16. readHolds.remove();
  17. if (count <= 0)
  18. throw unmatchedUnlockException();
  19. }
  20. --rh.count;
  21. }
  22. //利用自旋,将同步状态减去读状态(高16位)直到为0
  23. for (;;) {
  24. int c = getState();
  25. int nextc = c - SHARED_UNIT;
  26. if (compareAndSetState(c, nextc))
  27. // Releasing the read lock has no effect on readers,
  28. // but it may allow waiting writers to proceed if
  29. // both read and write locks are now free.
  30. return nextc == 0;
  31. }
  32. }

读锁的释放就是一个自旋CAS的过程,没有什么特殊的地方。

4:锁的降级(写锁降级为读锁,不支持锁升级)
读写锁支持锁降级,遵循按照获取写锁,获取读锁再释放写锁的次序,写锁能够降级成为读锁,不支持锁升级
例子如下:

  1. void processCachedData() {
  2. rwl.readLock().lock();
  3. if (!cacheValid) {
  4. // Must release read lock before acquiring write lock
  5. rwl.readLock().unlock(); //读锁必须先释放
  6. rwl.writeLock().lock(); //写锁锁定
  7. try {
  8. // Recheck state because another thread might have
  9. // acquired write lock and changed state before we did.
  10. if (!cacheValid) {
  11. data = ...
  12. cacheValid = true;
  13. }
  14. // Downgrade by acquiring read lock before releasing write lock
  15. rwl.readLock().lock();
  16. } finally {
  17. rwl.writeLock().unlock(); // Unlock write, still hold read
  18. }
  19. //锁降级完成,写锁降级为了读锁
  20. }
  21. try {
  22. use(data);
  23. } finally {
  24. rwl.readLock().unlock();
  25. }
  26. }
  27. }

对于锁降级的解释具体请看并发编程的艺术p145,锁降级即丢掉写锁,只保留读锁。

到这里,我们就分析完了读写锁,对于读写锁,需要记住,写锁是独占锁,读锁是共享锁,注意加锁流程必须是:先获取写锁,然后获取读锁,最后释放写锁,满足这个条件才能获取锁成功,这是本篇的重点,还有一个重点是读锁和写锁的同步状态是根据AQS中state的高16位与低16位分别保存的,记住这个规则才能理解读写锁的可重入与锁的释放。 还有就是利用非公平锁与公平锁类的重写方法返回值才在Sync中实现了非公平与公平锁的区别,至于原理与ReentrankLock没多大区别 。 最后是锁的降级,写锁是可以被降级为读锁的,通过先释放读锁,然后只有一个线程获取写锁,使得其他线程都陷入阻塞,这时再读锁加锁,释放写锁,其他线程就都可以被唤醒获取读锁,这就完成了锁降级,丢掉了写锁,只保留读锁。