赞
踩
ReentrantLock属于排他锁,这些锁在同一时刻只允许一个线程进行访问,而读写锁ReentrantReadWriterLock在同一时刻可以允许多个线程访问,但是在写线程访问时,所有的读和其他写线程都被阻塞。读写锁维护了一对锁,一个读锁和一个写锁,通过分离读锁和写锁,使得并发性相比一般的排他锁有了很大提升。
下面我们来看看读写锁ReentrantReadWriter特性
ReentrantReadWriterLock是ReadWriterLock的接口实现类,但是ReadWriterLock接口仅有读锁、写锁两个方法
- 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自己提供了一些内部工作状态方法,例如
- /**
- * 返回当前读锁被获取的次数,该次数不等于获取锁的线程数,因为同一个线程可以多次获取支持重入锁
- * Queries the number of read locks held for this lock. This
- * method is designed for use in monitoring system state, not for
- * synchronization control.
- * @return the number of read locks held.
- */
- public int getReadLockCount() {
- return sync.getReadLockCount();
- }
-
- /**
- * 返回当前线程获取读锁的次数,Java6之后使用ThreadLocal保存当前线程获取的次数
- */
- 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 == current.getId())
- return rh.count;
- int count = readHolds.get().count;
- if (count == 0) readHolds.remove();
- return count;
- }
-
- /**
- * 判断写锁是否被获取
- * @return
- */
- final boolean isWriteLocked() {
- return exclusiveCount(getState()) != 0;
- }
-
- /**
- * 判断当前写锁被获取的次数
- * @return
- */
- final int getWriteHoldCount() {
- return isHeldExclusively() ? exclusiveCount(getState()) : 0;
- }

下面我们来看一个通过缓存示例说明读写锁的使用
- public class Cache {
- static Map<String,Object> map = new HashMap<String,Object>();
- static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
- static Lock r = rwl.readLock();
- static Lock w = rwl.writeLock();
-
- public static final Object get(String key){
- r.lock();
- try {
- return map.get(key);
- } finally {
- r.unlock();
- }
- }
-
- public static final Object put(String key,String value){
- w.lock();
- try{
- return map.put(key, value);
- }finally{
- w.unlock();
- }
- }
-
- public static final void clear(){
- w.lock();
- try{
- map.clear();
- }finally{
- w.unlock();
- }
- }
-
- }

上面的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方法
- 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)
- // 存在读锁或者当前获取线程不是已经获取锁的线程
- 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;
- }

该方法除了重入条件(当前线程为获取了写锁的线程)之外,增加了一个读锁是否存在的判断。如果存在读锁,则写锁不能被获取,原因在于:读写锁要确保写锁的操作对读锁可见,如果允许读锁在已被获取的情况下对写锁的获取,那么正在运行的其他读线程就无法感知到当前写线程的操作。因此,只有等待其他读线程都释放了读锁,写锁才能被当前线程获取,而写锁一旦被获取,则其他读写线程的后续访问均被阻塞。写锁的释放与ReentrantLock的释放过程基本类似,每次释放均减少写状态,当写状态为0时表示写锁已被释放,从而等待的读写线程能够继续访问读写锁,同时前次写线程的修改对后续读写线程可见
读锁是一个支持重进入的共享锁,它能够被多个线程同时获取,在没有其他写线程访问(或者写状态为0)时,读锁总会被成功地获取,而所做的也只是(线程安全的)增加读状态。如果当前线程已经获取了读锁,则增加读状态。如果当前线程在获取读锁时,写锁已被其他线程获取,则进入等待状态。获取读锁的实现从Java 5到Java 6变得复杂许多,主要原因是新增了一些功能,例如getReadHoldCount()方法,作用是返回当前线程获取读锁的次数。读状态是所有线程获取读锁次数的总和,而每个线程各自获取读锁的次数只能选择保存在ThreadLocal中,由线程自身维护,这使获取读锁的实现变得复杂
- 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();
- 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 != current.getId())
- cachedHoldCounter = rh = readHolds.get();
- else if (rh.count == 0)
- readHolds.set(rh);
- rh.count++;
- }
- return 1;
- }
- return fullTryAcquireShared(current);
- }

在tryAcquireShared(int unused)方法中,如果其他线程已经获取了写锁,则当前线程获取读锁失败,进入等待状态。如果当前线程获取了写锁或者写锁未被获取,则当前线程(线程安全,依靠CAS保证)增加读状态,成功获取读锁。读锁的每次释放(线程安全的,可能有多个读线程同时释放读锁)均减少读状态,减少的值是(1<<16)
锁降级指的是写锁降级成为读锁。如果当前线程拥有写锁,然后将其释放,最后再获取读锁,这种分段完成的过程不能称之为锁降级。锁降级是指把持住(当前拥有的)写锁,再获取到读锁,随后释放(先前拥有的)写锁的过程。
在浏览ReentrantReadWriteLock的官方文档时,看到锁降级的示例代码
- class CachedData {
- Object data;
- volatile boolean cacheValid;
- final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
-
- void processCachedData() {
- rwl.readLock().lock();
- if (!cacheValid) {
- // Must release read lock before acquiring write lock
- rwl.readLock().unlock();
- rwl.writeLock().lock();
- try {
- // Recheck state because another thread might have
- // acquired write lock and changed state before we did.
- if (!cacheValid) {
- data = ...
- cacheValid = true;
- }
- // Downgrade by acquiring read lock before releasing write lock
- rwl.readLock().lock();
- } finally {
- rwl.writeLock().unlock(); // Unlock write, still hold read
- }
- }
-
- try {
- use(data);
- } finally {
- rwl.readLock().unlock();
- }
- }
- }

在释放写锁前,需要先获得读锁,然后再释放写锁。如果不先获取读锁,那么其他线程在这个线程释放写锁后可能会修改data,而这种修改对于这个线程是不可见的,从而在之后的use(data)中使用的是错误的值 。
答:不是必须的。
在这个问题里,如果不想使用锁降级
但问题是
锁降级只是提供了一个手段,这个手段可以让流程不被中断的降低到低级别锁,并且相对同样满足业务要求的其他手段性能更为良好。
读写锁虽然分离了读和写的功能,使得读与读之间可以完全并发,但是读和写之间依然是冲突的,读锁会完全阻塞写锁,它使用的依然是悲观的锁策略.如果有大量的读线程,他也有可能引起写线程的饥饿。
在JDK 1.8中引进了读写锁的一个改进版本,StampedLock,有兴趣可以了解一下Java并发编程笔记之StampedLock锁源码探究 - 国见比吕 - 博客园
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。