这篇讲讲ReentrantReadWriteLock可重入读写锁,它不仅是读写锁的实现,而且支持可重入性。 聊聊高并发(十五)实现一个简单的读-写锁(共享-排他锁) 这篇讲了怎样模拟一个读写锁。

可重入的读写锁的特点是

1. 当有线程获取读锁时,不同意再有线程获得写锁

2. 当有线程获得写锁时。不同意其它线程获得读锁和写锁

这里隐含着几层含义:

 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; }

1. 能够同一时候有多个线程同一时候获得读锁,进入临界区。这时候的读锁的行为和Semaphore信号量是类似的

2. 因为是可重入的。所以1个线程假设获得了读锁,那么它能够重入这个读锁

3. 假设1个线程获得了读锁。那么它不能同一时候再获得写锁,这个就是所谓的“锁升级”,读锁升级到写锁可能会造成死锁,所以是不同意的

4. 假设1个线程获得了写锁,那么不同意其它线程再获得读锁和写锁,可是它自己能够获得读锁,就是所谓的“锁降级”,锁降级是同意的

关于读写锁的实现还要考虑的几个要点:

1. 释放锁时的优先级问题。是让写锁先获得还是先让读锁先获得

2. 是否同意读线程插队

3. 是否同意写线程插队。由于读写锁一般用在大量读,少量写的情况,假设写线程没有优先级,那么可能造成写线程的饥饿

4. 锁的升降级问题,通常是同意1个线程的写锁降级为读锁,不同意读锁升级成写锁

带着问题看看ReentrantReadWriteLock的源代码。 它相同提供了Sync来继承AQS并提供扩展,可是它的Sync相比較Semaphore和CountDownLatch要更加复杂。

1. 把State状态作为一个读写锁的计数器,包含了重入的次数。

state是32位的int值,所以把高位16位作为读锁的计数器,低位的16位作为写锁的计数器,并提供了响应的读写这两个计数器的位操作方法。

计算sharedCount时,採用无符号的移位操作,右移16位就是读锁计数器的值

写锁直接用EXCLUSIVE_MASK和state做与运算。EXCLUSIVE_MASK的值是00000000000000001111111111111111,相当于计算了低位16位的值

须要注意计算出来的值包括了重入的次数。

所以MAX_COUNT限定了最大值是2^17 - 1

 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; }

HoldCount类用来计算1个线程的重入次数,并使用了1个ThreadLocal类型的HoldCounter,能够记录每一个线程的锁的重入次数。 cachedHoldCounter记录了最后1个获取读锁的线程的重入次数。 firstReader指向了第一个获取读锁的线程,firstReaderHoldCounter记录了第一个获取读锁的线程的重入次数

static final class HoldCounter {
int count = 0;
// Use id, not reference, to avoid garbage retention
final long tid = Thread.currentThread().getId();
} /**
* 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 hold count of the last thread to successfully acquire
         * readLock. This saves ThreadLocal lookup in the common case
         * where the next thread to release is the last one to
         * acquire. This is non-volatile since it is just used
         * as a heuristic, and would be great for threads to cache.
         *
         * <p>Can outlive the Thread for which it is caching the read
         * hold count, but avoids garbage retention by not retaining a
         * reference to the Thread.
         *
         * <p>Accessed via a benign data race; relies on the memory
         * model's final field and out-of-thin-air guarantees.
         */
        private transient HoldCounter cachedHoldCounter;

Sync提供了两个抽象方法给子类扩展。用来表示读锁和写锁是否应该堵塞等待

/**
* Returns true if the current thread, when trying to acquire
* the read lock, and otherwise eligible to do so, should block
* because of policy for overtaking other waiting threads.
*/
abstract boolean readerShouldBlock(); /**
* Returns true if the current thread, when trying to acquire
* the write lock, and otherwise eligible to do so, should block
* because of policy for overtaking other waiting threads.
*/
abstract boolean writerShouldBlock();

写锁的tryXXX获取和释放

1. 写锁释放时,因为没有其它线程获得临界区。它的tryRelease()方法仅仅须要设置状态的值。通过exclusiveCount计算写锁的计数器,假设为0表示释放了写锁,就把exclusiveOwnerThread设置为null.

2. 写锁的tryAcquire获取时。

先推断状态是否为0,为0表示没有线程获得锁,就能够直接设置状态。然后把exclusiveOwnerThread设置为当前线程

假设状态不为0,那表示有几种可能:写锁为0。读锁不为0。写锁不为0。读锁为0。写锁不为0,读锁也不为0。

所以它先推断写锁是否为0。写锁为0,那么表示读锁肯定不会为0,就失败,

或者写锁不为0,可是exclusiveOwnerThread不是自己。那么表示已经有其它线程获得了写锁,就失败

写锁不为0,而且exclusiveOwnerThread是自己。那么肯定表示是写锁的重入的情况,所以设置state状态。返回成功。

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;
} 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;
        }

读锁的tryXXX获取和释放

1. 读锁释放时基于共享的方式,改动线程各自的HoldCounter的值。最后採用位操作改动位于state的整体的读锁计数器。tryReleaseShared()之后详细的释放兴许线程的操作由AQS依据队列状态来决定。

2. 读所获取时先看写锁的计数器,假设写锁已经被获取。而且不是当前线程所获取的。就直接失败返回

这里会进行一次高速路径获取,尝试获取一次,假设readShouldBlock()返回false,而且CAS操作成功了,意思是能够获得锁,就更新相关读锁计数器

否则就进行轮询方式的获取fullTryAcquireShared()

也就是说假设当前没有线程获取写锁,或者是自己获取写锁。就能够获取读锁

一个线程获取了写锁之后,它还能够获取读锁,也就是所谓的“锁降级”,但这时候其它线程无法获取读锁。在检查到有其它写锁存在时就退出了

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 != current.getId())
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;
}
} 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);
        }  /**
         * Full version of acquire for reads, that handles CAS misses
         * and reentrant reads not dealt with in tryAcquireShared.
         */
        final int fullTryAcquireShared(Thread current) {
            /*
             * This code is in part redundant with that in
             * tryAcquireShared but is simpler overall by not
             * complicating tryAcquireShared with interactions between
             * retries and lazily reading hold counts.
             */
            HoldCounter rh = cachedHoldCounter;
            if (rh == null || rh.tid != current.getId())
                rh = readHolds.get();
            for (;;) {
                int c = getState();
                int w = exclusiveCount(c);
                if ((w != 0 && getExclusiveOwnerThread() != current) ||
                    ((rh.count | w) == 0 && readerShouldBlock(current)))
                    return -1;
                if (sharedCount(c) == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                if (compareAndSetState(c, c + SHARED_UNIT)) {
                    cachedHoldCounter = rh; // cache for release
                    rh.count++;
                    return 1;
                }
            }
        } 

tryWriteLock和tryReadLock操作和上面的操作类似,它们是读写锁的tryLock()的实际实现,表示尝试获取一次锁

1. tryWriteLock方法尝试获得写锁,先推断状态是否为0,为0而且CAS操作成功就表示获得锁。假设状态不为0,就推断写锁计数器的值。假设写锁计数器为0就表示存在读锁,就返回失败。获取写锁不为0,可是不是当前线程所获取的,也返回失败。仅仅有写锁不为0而且是当前线程自己获取的写锁,就是所谓的写锁重入操作。

CAS成功后就表示获得写锁

final boolean tryWriteLock() {
Thread current = Thread.currentThread();
int c = getState();
if (c != 0) {
int w = exclusiveCount(c);
if (w == 0 ||current != getExclusiveOwnerThread())
return false;
if (w == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
}
if (!compareAndSetState(c, c + 1))
return false;
setExclusiveOwnerThread(current);
return true;
} final boolean tryReadLock() {
            Thread current = Thread.currentThread();
            for (;;) {
                int c = getState();
                if (exclusiveCount(c) != 0 &&
                    getExclusiveOwnerThread() != current)
                    return false;
                if (sharedCount(c) == MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                if (compareAndSetState(c, c + SHARED_UNIT)) {
                    HoldCounter rh = cachedHoldCounter;
                    if (rh == null || rh.tid != current.getId())
                        cachedHoldCounter = rh = readHolds.get();
                    rh.count++;
                    return true;
                }
            }
        }

ReentrantReadWriteLock也提供了非公平和公平的两个Sync版本号

非公平的版本号中

1. 写锁总是优先获取。不考虑AQS队列中先来的线程

2. 读锁也不按FIFO队列排队,而是看当前获得锁是否是写锁,假设是写锁,就等待。否则就尝试获得锁

而公平版本号中

1. 假设有其它锁存在,获取写锁操作就失败。应该(should)进AQS队列等待

2. 假设有其它锁存在。获取读锁操作就失败。应该(should)进AQS队列等待

final static class NonfairSync extends Sync {
private static final long serialVersionUID = -8159625535654395037L;
final boolean writerShouldBlock(Thread current) {
return false; // writers can always barge
}
final boolean readerShouldBlock(Thread current) {
/* As a heuristic to avoid indefinite writer starvation,
* block if the thread that momentarily appears to be head
* of queue, if one exists, is a waiting writer. This is
* only a probablistic effect since a new reader will not
* block if there is a waiting writer behind other enabled
* readers that have not yet drained from the queue.
*/
return apparentlyFirstQueuedIsExclusive();
}
} /**
* Fair version of Sync
*/
final static class FairSync extends Sync {
private static final long serialVersionUID = -2274990926593161451L;
final boolean writerShouldBlock(Thread current) {
// only proceed if queue is empty or current thread at head
return !isFirst(current);
}
final boolean readerShouldBlock(Thread current) {
// only proceed if queue is empty or current thread at head
return !isFirst(current);
}
}

详细ReadLock和WriteLock的实现就是依赖Sync来实现的,默认是非公平版本号的Sync。

读锁採用共享默认的AQS,它提供了中断/不可中断的lock操作,tryLock操作,限时的tryLock操作。

值得注意的时读锁不支持newCondition操作。

 public static class ReadLock implements Lock, java.io.Serializable  {
private static final long serialVersionUID = -5992448646407690164L;
private final Sync sync; protected ReadLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
} public void lock() {
sync.acquireShared(1);
}   public void lockInterruptibly() throws InterruptedException {
            sync.acquireSharedInterruptibly(1);
        } public  boolean tryLock() {
            return sync.tryReadLock();
        } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
            return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
        } public  void unlock() {
            sync.releaseShared(1);
        }   public Condition newCondition() {
            throw new UnsupportedOperationException();
        }

WriteLock基于独占模式的AQS,它提供了中断/不可中断的lock操作。tryLock操作,限时的tryLock操作

 public static class WriteLock implements Lock, java.io.Serializable  {
private static final long serialVersionUID = -4992448646407690164L;
private final Sync sync; protected WriteLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}   public void lock() {
            sync.acquire(1);
        }  public void lockInterruptibly() throws InterruptedException {
            sync.acquireInterruptibly(1);
        } public boolean tryLock( ) {
            return sync.tryWriteLock();
        } public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
        } public void unlock() {
            sync.release(1);
        } public Condition newCondition() {
            return sync.newCondition();
        }

最后再说一下AQS和各种同步器实现的关系,AQS提供了同步队列和条件队列的管理。包含各种情况下的入队出队操作。

而同步器子类实现了tryAcquire和tryRelease方法来操作状态。来表示什么情况下能够直接获得锁而不须要进入AQS。什么情况下获取锁失败则须要进入AQS队列等待

聊聊高并发(二十八)解析java.util.concurrent各个组件(十) 理解ReentrantReadWriteLock可重入读-写锁的更多相关文章

  1. 聊聊高并发(二十)解析java.util.concurrent各个组件(二) 12个原子变量相关类

    这篇说说java.util.concurrent.atomic包里的类,总共12个.网上有非常多文章解析这几个类.这里挑些重点说说. watermark/2/text/aHR0cDovL2Jsb2cu ...

  2. 谈论高并发(三十)解析java.util.concurrent各种组件(十二) 认识CyclicBarrier栅栏

    这次谈话CyclicBarrier栅栏,如可以从它的名字可以看出,它是可重复使用. 它的功能和CountDownLatch类别似,也让一组线程等待,然后开始往下跑起来.但也有在两者之间有一些差别 1. ...

  3. 聊聊高并发(四十)解析java.util.concurrent各个组件(十六) ThreadPoolExecutor源代码分析

    ThreadPoolExecutor是Executor运行框架最重要的一个实现类.提供了线程池管理和任务管理是两个最主要的能力.这篇通过分析ThreadPoolExecutor的源代码来看看怎样设计和 ...

  4. 聊聊高并发(二十九)解析java.util.concurrent各个组件(十一) 再看看ReentrantReadWriteLock可重入读-写锁

    上一篇聊聊高并发(二十八)解析java.util.concurrent各个组件(十) 理解ReentrantReadWriteLock可重入读-写锁 讲了可重入读写锁的基本情况和基本的方法,显示了怎样 ...

  5. 聊聊高并发(二十五)解析java.util.concurrent各个组件(七) 理解Semaphore

    前几篇分析了一下AQS的原理和实现.这篇拿Semaphore信号量做样例看看AQS实际是怎样使用的. Semaphore表示了一种能够同一时候有多个线程进入临界区的同步器,它维护了一个状态表示可用的票 ...

  6. 018-并发编程-java.util.concurrent.locks之-ReentrantReadWriteLock可重入读写锁

    一.概述 ReentrantLock是一个排他锁,同一时间只允许一个线程访问,而ReentrantReadWriteLock允许多个读线程同时访问,但不允许写线程和读线程.写线程和写线程同时访问.相对 ...

  7. 聊聊高并发(三十八)解析java.util.concurrent各个组件(十四) 理解Executor接口的设计

    JUC包中除了一系列的同步类之外,就是Executor运行框架相关的类.对于一个运行框架来说,能够分为两部分 1. 任务的提交 2. 任务的运行. 这是一个生产者消费者模式,提交任务的操作是生产者,运 ...

  8. 聊聊高并发(二十四)解析java.util.concurrent各个组件(六) 深入理解AQS(四)

    近期总体过了下AQS的结构.也在网上看了一些讲AQS的文章,大部分的文章都是泛泛而谈.又一次看了下AQS的代码,把一些新的要点拿出来说一说. AQS是一个管程.提供了一个主要的同步器的能力,包括了一个 ...

  9. 聊聊高并发(四十四)解析java.util.concurrent各个组件(二十) Executors工厂类

    Executor框架为了更方便使用,提供了Executors这个工厂类.通过一系列的静态工厂方法.能够高速地创建对应的Executor实例. 仅仅有一个nThreads參数的newFixedThrea ...

随机推荐

  1. HNU 12961 BitTorrent DP

    题意: 你在网上下载东西,一个文件存储在一段或者多段里面,问怎么选择能在规定的流量内下载最多的文件数量.每段的大小一样. 思路: 习惯了做答案保存在DP数组里的题,做这种答案保存在下标里的题,转不过弯 ...

  2. 第三讲 $\mathbb{R}^4$上平凡主丛的联络、曲率与Yang-Mills泛函

    一. $\mathbb{R}^4$或$\mathbb{R}^n$上平凡主丛的联络与曲率$\newcommand{\R}{\mathbb{R}}$ 回忆切丛$T\R^n\cong \R^n\times\ ...

  3. C# 从需要登录的网站上抓取数据

    [转] C# 从需要登录的网站上抓取数据 背景:昨天一个学金融的同学让我帮她从一个网站上抓取数据,然后导出到excel,粗略看了下有1000+条记录,人工统计的话确实不可能.虽说不会,但作为一个学计算 ...

  4. 移动App架构设计

    移动App架构设计 本文主要总结了几种经常使用的架构模式, 基本是层层递进的转载请注名出处 http://blog.csdn.net/uxyheaven, 良好的排版在https://github.c ...

  5. 最简单的HTML5游戏——贪吃蛇

    <html> <head> <meta charset="UTF-8"/> <title>贪吃蛇</title> < ...

  6. FPGA设计中的电源管理(转载)

    过去,FPGA设计者主要关心时序和面积使用率问题.但随着FPGA不断取代ASSP和ASIC器件,设计者们现正期望能够开发低功耗设计,在设计流程早期就能对功耗进行正确估算,以及管理和对与FPGA相关的各 ...

  7. React开发实时聊天招聘工具 -第六章 登陆注册(2)

    1.bodyParser和cookieParser:   const bodyParser = require('body-parser') const cookieParser = require( ...

  8. Hexo 相册实践

    灵感 想给自已的blog添加一个相册功能.给生活中的点点滴滴留影记录.搜寻网络上给Next主题添加相册功能的基本上没有,只能重头到尾开始一点点的实践.    大致的想法:  1. 相册展示类似于归档一 ...

  9. 【Linux端口大全】

    2端口:管理实用程序 3端口:压缩进程 5端口:远程作业登录 7端口:回显 9端口:丢弃 11端口:在线用户 13端口:时间 17端口:每日引用 18端口:消息发送协议 19端口:字符发生器 20端口 ...

  10. jQuery对checkbox选中和取消选中操作

    最近做项目发现jQuery对checkbox的全选和非全选操作只有第一次生效,以后就不生效了,不知道是不是jQuery版本库的问题,最终找到了一个解决方案: 把原来的下面这两句: $('input') ...