当前位置:   article > 正文

Java读写锁ReentrantReadWriteLock原理详解_java reentrantreadwritelock

java reentrantreadwritelock

介绍

ReentrantLock属于排他锁,这些锁在同一时刻只允许一个线程进行访问,而读写锁ReentrantReadWriterLock在同一时刻可以允许多个线程访问,但是在写线程访问时,所有的读和其他写线程都被阻塞。读写锁维护了一对锁,一个读锁和一个写锁,通过分离读锁和写锁,使得并发性相比一般的排他锁有了很大提升。 
下面我们来看看读写锁ReentrantReadWriter特性 

  1. 公平性选择:支持非公平(默认)和公平的锁获取模式,非公平的吞吐量优于公平; 
  2. 重入性:该锁支持重入锁,以读写线程为例:读线程在获取读锁之后,能够再次读取读锁,而写线程在获取写锁之后可以同时再次获取读锁和写锁 ;
  3. 锁降级:遵循获取写锁,获取读锁再释放写锁的次序,写锁能够降级为读锁;

读写锁接口详解

ReentrantReadWriterLock是ReadWriterLock的接口实现类,但是ReadWriterLock接口仅有读锁、写锁两个方法

  1. public interface ReadWriteLock {
  2.     /**
  3.      * Returns the lock used for reading.
  4.      *
  5.      * @return the lock used for reading.
  6.      */
  7.     Lock readLock();
  8.     /**
  9.      * Returns the lock used for writing.
  10.      *
  11.      * @return the lock used for writing.
  12.      */
  13.     Lock writeLock();
  14. }

ReentrantReadWriteLock自己提供了一些内部工作状态方法,例如

  1.  /**
  2.      * 返回当前读锁被获取的次数,该次数不等于获取锁的线程数,因为同一个线程可以多次获取支持重入锁
  3.      * Queries the number of read locks held for this lock. This
  4.      * method is designed for use in monitoring system state, not for
  5.      * synchronization control.
  6.      * @return the number of read locks held.
  7.      */
  8.     public int getReadLockCount() {
  9.         return sync.getReadLockCount();
  10.     }
  11.     /**
  12.      * 返回当前线程获取读锁的次数,Java6之后使用ThreadLocal保存当前线程获取的次数
  13.      */
  14.     final int getReadHoldCount() {
  15.         if (getReadLockCount() == 0)
  16.             return 0;
  17.         Thread current = Thread.currentThread();
  18.         if (firstReader == current)
  19.             return firstReaderHoldCount;
  20.         HoldCounter rh = cachedHoldCounter;
  21.         if (rh != null && rh.tid == current.getId())
  22.             return rh.count;
  23.         int count = readHolds.get().count;
  24.         if (count == 0) readHolds.remove();
  25.         return count;
  26.     }
  27.     /**
  28.      * 判断写锁是否被获取
  29.      * @return
  30.      */
  31.     final boolean isWriteLocked() {
  32.         return exclusiveCount(getState()) != 0;
  33.     }
  34.     /**
  35.      * 判断当前写锁被获取的次数
  36.      * @return
  37.      */
  38.     final int getWriteHoldCount() {
  39.         return isHeldExclusively() ? exclusiveCount(getState()) : 0;
  40.     }

下面我们来看一个通过缓存示例说明读写锁的使用

  1. public class Cache {
  2.     static Map<String,Object> map = new HashMap<String,Object>();
  3.     static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
  4.     static Lock r = rwl.readLock();
  5.     static Lock w = rwl.writeLock();
  6.     public static final Object get(String key){
  7.         r.lock();
  8.         try {
  9.             return map.get(key);
  10.         } finally {
  11.             r.unlock();
  12.         }
  13.     }
  14.     public static final Object put(String key,String value){
  15.         w.lock();
  16.         try{
  17.             return map.put(key, value);
  18.         }finally{
  19.             w.unlock();
  20.         }
  21.     }
  22.     public static final void clear(){
  23.         w.lock();
  24.         try{
  25.             map.clear();
  26.         }finally{
  27.             w.unlock();
  28.         }
  29.     }
  30. }

上面的HashMap虽然是非线程安全,但是我们在get和put时候分别使用读写锁,保证了线程安全。

读写锁的实现原理分析

读写状态的设计

读写锁同样依赖自定义同步器来实现同步功能,而读写状态就是其同步器的同步状态。回想ReentrantLock中自定义同步器的实现,同步状态表示锁被一个线程重复获取的次数,而读写锁的自定义同步器需要在同步状态(一个整型变量)上维护多个读线程和一个写线程的状态,使得该状态的设计成为读写锁实现的关键。如果在一个整型变量上维护多种状态,就一定需要“按位切割使用”这个变量,读写锁将变量切分成了两个部分,高16位表示读,低16位表示写,划分方式如下图所示 

读写锁状态

当前同步状态表示一个线程已经获取了写锁,且重进入了两次,同时也连续获取了两次读锁。读写锁是如何迅速确定读和写各自的状态呢?答案是通过位运算。假设当前同步状态值为S,写状态等于S&0x0000FFFF(将高16位全部抹去),读状态等于S>>>16(无符号补0右移16位)。当写状态增加1时,等于S+1,当读状态增加1时,等于S+(1<<16),也就是S+0x00010000。根据状态的划分能得出一个推论:S不等于0时,当写状态(S&0x0000FFFF)等于0时,则读状态(S>>>16)大于0,即读锁已被获取。

写锁的获取与释放

写锁是一个支持重进入的排他锁。如果当前线程已经获取了写锁,则增加写状态。如果当前线程在获取写锁时,读锁已经被获取(读状态不为0)或者该线程不是已经获取写锁的线程,则当前线程进入等待状态,我们看下ReentrantReadWriteLock的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();
  15.             int w = exclusiveCount(c);
  16.             if (c != 0) {
  17.                 // (Note: if c != 0 and w == 0 then shared count != 0)
  18.                 // 存在读锁或者当前获取线程不是已经获取锁的线程
  19.                 if (w == 0 || current != getExclusiveOwnerThread())
  20.                     return false;
  21.                 if (w + exclusiveCount(acquires) > MAX_COUNT)
  22.                     throw new Error("Maximum lock count exceeded");
  23.                 // Reentrant acquire
  24.                 setState(c + acquires);
  25.                 return true;
  26.             }
  27.             if (writerShouldBlock() ||
  28.                 !compareAndSetState(c, c + acquires))
  29.                 return false;
  30.             setExclusiveOwnerThread(current);
  31.             return true;
  32.         }

该方法除了重入条件(当前线程为获取了写锁的线程)之外,增加了一个读锁是否存在的判断。如果存在读锁,则写锁不能被获取,原因在于:读写锁要确保写锁的操作对读锁可见,如果允许读锁在已被获取的情况下对写锁的获取,那么正在运行的其他读线程就无法感知到当前写线程的操作。因此,只有等待其他读线程都释放了读锁,写锁才能被当前线程获取,而写锁一旦被获取,则其他读写线程的后续访问均被阻塞。写锁的释放与ReentrantLock的释放过程基本类似,每次释放均减少写状态,当写状态为0时表示写锁已被释放,从而等待的读写线程能够继续访问读写锁,同时前次写线程的修改对后续读写线程可见

读锁的获取与释放

读锁是一个支持重进入的共享锁,它能够被多个线程同时获取,在没有其他写线程访问(或者写状态为0)时,读锁总会被成功地获取,而所做的也只是(线程安全的)增加读状态。如果当前线程已经获取了读锁,则增加读状态。如果当前线程在获取读锁时,写锁已被其他线程获取,则进入等待状态。获取读锁的实现从Java 5到Java 6变得复杂许多,主要原因是新增了一些功能,例如getReadHoldCount()方法,作用是返回当前线程获取读锁的次数。读状态是所有线程获取读锁次数的总和,而每个线程各自获取读锁的次数只能选择保存在ThreadLocal中,由线程自身维护,这使获取读锁的实现变得复杂

  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.             if (exclusiveCount(c) != 0 &&
  20.                 getExclusiveOwnerThread() != current)
  21.                 return -1;
  22.             int r = sharedCount(c);
  23.             if (!readerShouldBlock() &&
  24.                 r < MAX_COUNT &&
  25.                 compareAndSetState(c, c + SHARED_UNIT)) {
  26.                 if (r == 0) {
  27.                     firstReader = current;
  28.                     firstReaderHoldCount = 1;
  29.                 } else if (firstReader == current) {
  30.                     firstReaderHoldCount++;
  31.                 } else {
  32.                     HoldCounter rh = cachedHoldCounter;
  33.                     if (rh == null || rh.tid != current.getId())
  34.                         cachedHoldCounter = rh = readHolds.get();
  35.                     else if (rh.count == 0)
  36.                         readHolds.set(rh);
  37.                     rh.count++;
  38.                 }
  39.                 return 1;
  40.             }
  41.             return fullTryAcquireShared(current);
  42.         }

在tryAcquireShared(int unused)方法中,如果其他线程已经获取了写锁,则当前线程获取读锁失败,进入等待状态。如果当前线程获取了写锁或者写锁未被获取,则当前线程(线程安全,依靠CAS保证)增加读状态,成功获取读锁。读锁的每次释放(线程安全的,可能有多个读线程同时释放读锁)均减少读状态,减少的值是(1<<16)

锁降级

锁降级指的是写锁降级成为读锁。如果当前线程拥有写锁,然后将其释放,最后再获取读锁,这种分段完成的过程不能称之为锁降级。锁降级是指把持住(当前拥有的)写锁,再获取到读锁,随后释放(先前拥有的)写锁的过程。

在浏览ReentrantReadWriteLock的官方文档时,看到锁降级的示例代码

  1. class CachedData {
  2. Object data;
  3. volatile boolean cacheValid;
  4. final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
  5. void processCachedData() {
  6. rwl.readLock().lock();
  7. if (!cacheValid) {
  8. // Must release read lock before acquiring write lock
  9. rwl.readLock().unlock();
  10. rwl.writeLock().lock();
  11. try {
  12. // Recheck state because another thread might have
  13. // acquired write lock and changed state before we did.
  14. if (!cacheValid) {
  15. data = ...
  16. cacheValid = true;
  17. }
  18. // Downgrade by acquiring read lock before releasing write lock
  19. rwl.readLock().lock();
  20. } finally {
  21. rwl.writeLock().unlock(); // Unlock write, still hold read
  22. }
  23. }
  24. try {
  25. use(data);
  26. } finally {
  27. rwl.readLock().unlock();
  28. }
  29. }
  30. }

在释放写锁前,需要先获得读锁,然后再释放写锁。如果不先获取读锁,那么其他线程在这个线程释放写锁后可能会修改data,而这种修改对于这个线程是不可见的,从而在之后的use(data)中使用的是错误的值 。

使用java的ReentrantReadWriteLock读写锁时,锁降级是必须的么?

答:不是必须的。

在这个问题里,如果不想使用锁降级

  1. 可以继续持有写锁,完成后续的操作。
  2. 也可以先把写锁释放,再获取读锁。

但问题是

  1. 如果继续持有写锁,如果 use 函数耗时较长,那么就不必要的阻塞了可能的读流程
  2. 如果先把写锁释放,再获取读锁。在有些逻辑里,这个 cache 值可能被修改也可能被移除,这个看能不能接受。另外,降级锁比释放写再获取读性能要好,因为当前只有一个写锁,可以直接不竞争的降级。而先释放写锁,再获取读锁的过程就需要面对其他读锁请求的竞争,引入额外不必要的开销。

锁降级只是提供了一个手段,这个手段可以让流程不被中断的降低到低级别锁,并且相对同样满足业务要求的其他手段性能更为良好。

读写锁虽然分离了读和写的功能,使得读与读之间可以完全并发,但是读和写之间依然是冲突的,读锁会完全阻塞写锁,它使用的依然是悲观的锁策略.如果有大量的读线程,他也有可能引起写线程的饥饿。

在JDK 1.8中引进了读写锁的一个改进版本,StampedLock,有兴趣可以了解一下Java并发编程笔记之StampedLock锁源码探究 - 国见比吕 - 博客园

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号