前言:

  在Java的锁中很多锁都是同一时刻只允许一个线程访问,今天就来看看一个特殊的锁——读写锁。它的特殊之处就在于同一时刻可以运行多个读线程访问或者有一个写线程在访问。能够大大的提高并发性和吞吐量

ReentrantReadWriteLock介绍

  读写锁是一种特殊的自旋锁。在读写锁的世界里,访问共享资源的线程被划分为两类:一类是只对共享资源进行访问而不更改,暂且认为他是读者;一类是改变共享资源,即写操作,是写者。这个锁的核心要求是在没有任何线程获得读锁和写锁的情况才能获得写锁。

ReentrantReadWriteLock特性

  公平性:读写锁支持非公平和公平的锁获取方式,非公平锁的吞吐量优于公平锁的吞吐量,默认构造的是非公平锁

  可重入:在线程获取读锁之后能够再次获取读锁,但是不能获取写锁,而线程在获取写锁之后能够再次获取写锁,同时也能获取读锁

  锁降级:线程获取写锁之后获取读锁,再释放写锁,这样实现了写锁变为读锁,也叫锁降级

ReentrantReadWriteLock的内部类Sync核心源码解析

  1、类的属性

 abstract static class Sync extends AbstractQueuedSynchronizer {
// 版本序列号
private static final long serialVersionUID = 6317671515068378041L;
// 通过将整形变量state切成两部分,高16位表示读,低16位表示写,来区分读写状态。
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;
// 本地线程计数器
private transient ThreadLocalHoldCounter readHolds;
// 缓存的计数器
private transient HoldCounter cachedHoldCounter;
// 第一个读线程
private transient Thread firstReader = null;
// 第一个读线程的计数
private transient int firstReaderHoldCount;
}

  在ReentrantReadWriteLock中,读写状态的区分是其同步容器Sync的同步状态。而在Sync中应该有读线程的两种和写线程的两种状态。但是通常整形变量只能表示两种状态,这里需要四种所以就将整形变量分成高16位和低16位

  上图的同步状态表示一个线程已经获取了写锁,且重进入了两次,同时也连续获取了两次读锁。这个状态如何快速获取呢?

static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }

  上面这个方法能快速获得读状态,通过当前状态的无符号补0右移,能够将高16的状态移到低16位从而得到正常的数值状态。

static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

  上面这个方法则是快速获取写状态,直接将高16位抹去(相当于c&0x0000FFFF)

  2、写锁的释放和获取

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

  tryRelease:先判断是否拿到的是独占的资源,不是就表示可能线程拿的是读锁或者没有锁,这时候直接抛异常。如果是写锁那么就判断释放的锁的个数是否是当前锁的数量,是就释放所有写锁并且设置状态,否则就只设置状态。

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

  tryAcquire:首先这个方法会先获取state和线程的写锁个数,如果当前线程拿到了锁那么就判断拿的是否是写锁,如果ReentrantReadWriteLock存在读锁或者当先线程不是获取写锁的线程(即不是获取独占资源的线程),那么直接返回false,否则,根据可重入原则是可以获取锁的。或者另外一种情况就是当前线程没有拿到锁,然后在公平和非公平的情况下判断当前线程是否该被阻塞(公平情况下是看队列头部的直接后继,非公平就竞争),如果线程不该被阻塞就可以获取到锁。这时候获取的是写锁。

  3、读锁的释放和获取

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

  tryReleaseShared:主要是表示读锁线程释放锁。如果当前线程是第一个读线程且占有资源数firstReaderHoldCount为1,则可以直接释放该读线程,否则就firstReaderHoldCount减1。如果当前线程不是第一个读线程就会拿缓存计数器,用缓存计数器判断当前线程是否被缓存了或者是否是当前线程。如果计数器的值在缓存中,并且是当前的线程,那么就获取计数器中的计数count,否则还需要获取当前线程的计数器。获取完计数count之后计数值小于等于1就直接移除当前线程的计数器,而后count小于等于0就抛异常,否则就减少计数即可。之后就会进入无限循环,循环能够确保成功设置state。上述函数就是释放读锁,只不过对于当前线程是否是第一个读线程分两种情况来释放,最终能够获得state。

 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 != getThreadId(current))
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
}
return 1;
}
return fullTryAcquireShared(current);
}

  tryAcquireShared:获取读锁。首先就是当前线程为写线程或是独占锁的线程那么就会直接返回-1,当前线程不是写线程也不是独占的线程就获取ReentrantReadWriteLock的读锁数量判断读线程不应该被阻塞(分公平和不公平)并且小于读锁数量的最大值,并且设置状态成功。如果当前没有线程获取读锁,则这个线程就是第一个读线程,并且设置第一个读线程firstReader和firstReaderHoldCount;。如果当前线程为第一个读线程,只需要增加firstReaderHoldCount。上述两种情况不满足就设置当前线程对应的计数器HoldCounter。

 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 = null;
for (;;) {
int c = getState();
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)
return -1;
// else we hold the exclusive lock; blocking here
// would cause deadlock.
} else if (readerShouldBlock()) {
// Make sure we're not acquiring read lock reentrantly
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
} else {
if (rh == null) {
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current)) {
rh = readHolds.get();
if (rh.count == 0)
readHolds.remove();
}
}
if (rh.count == 0)
return -1;
}
}
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
if (compareAndSetState(c, c + SHARED_UNIT)) {
if (sharedCount(c) == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
firstReaderHoldCount++;
} else {
if (rh == null)
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
cachedHoldCounter = rh; // cache for release
}
return 1;
}
}
}

  fullTryAcquireShared:如果读线程被阻塞或者大于最大值,或者比较设置没成功。那么就会无限循环tryAcquireShared使得线程一定能获取读锁,如果是大于最大值则会抛异常。过程与tryAcquireShared类似。

  4、直接竞争锁

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

  tryWriteLock:实现机制与tryAcquire类似,但是区别在于不会去检查是否该线程获取写锁是否会被阻塞,直接让线程尝试竞争锁。

 final boolean tryReadLock() {
Thread current = Thread.currentThread();
for (;;) {
int c = getState();
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
return false;
int r = sharedCount(c);
if (r == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
if (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 true;
}
}
}

  tryReadLock:与实现机制tryAcquireShared,同样是直接让线程去竞争读锁

总结

  再提醒一下就是读写锁的核心要求是在没有任何线程获得读锁和写锁的情况才能获得写锁。可以实现锁的降级(当前线程拥有写锁且还没释放的情况拿到读锁,再释放写锁,实现了写锁到读锁的转换),但无法实现锁的升级,同样支持可重入和公平锁与非公平锁。相比于ReentrantLock提高了线程访问资源的吞吐量。

深入解析ReentrantReadWriteLock的更多相关文章

  1. 深入浅出ReentrantReadWriteLock源码解析

    读写锁实现逻辑相对比较复杂,但是却是一个经常使用到的功能,希望将我对ReentrantReadWriteLock的源码的理解记录下来,可以对大家有帮助 前提条件 在理解ReentrantReadWri ...

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

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

  3. ReentrantReadWriteLock 读写锁解析

    4 java中锁是个很重要的概念,当然这里的前提是你会涉及并发编程. 除了语言提供的锁关键字 synchronized和volatile之外,jdk还有其他多种实用的锁. 不过这些锁大多都是基于AQS ...

  4. 死磕 java同步系列之ReentrantReadWriteLock源码解析

    问题 (1)读写锁是什么? (2)读写锁具有哪些特性? (3)ReentrantReadWriteLock是怎么实现读写锁的? (4)如何使用ReentrantReadWriteLock实现高效安全的 ...

  5. Java并发包源码学习系列:ReentrantReadWriteLock读写锁解析

    目录 ReadWriteLock读写锁概述 读写锁案例 ReentrantReadWriteLock架构总览 Sync重要字段及内部类表示 写锁的获取 void lock() boolean writ ...

  6. Java并发之ReentrantReadWriteLock源码解析(一)

    ReentrantReadWriteLock 前情提要:在学习本章前,需要先了解笔者先前讲解过的ReentrantLock源码解析和Semaphore源码解析,这两章介绍了很多方法都是本章的铺垫.下面 ...

  7. Java并发之ReentrantReadWriteLock源码解析(二)

    先前,笔者和大家一起了解了ReentrantReadWriteLock的写锁实现,其实写锁本身实现的逻辑很少,基本上还是复用AQS内部的等待队列思想.下面,我们来看看ReentrantReadWrit ...

  8. 【JUC源码解析】ReentrantReadWriteLock

    简介 ReentrantReadWriteLock, 可重入读写锁,包括公平锁和非公平锁,相比较公平锁而言,非公平锁有更好的吞吐量,但可能会出现队列里的线程无限期地推迟一个或多个读线程或写线程的情况, ...

  9. Java 1.7 ReentrantReadWriteLock源代码解析

    因为本人水平与表达能力有限,有错误的地方欢迎交流与指正. 1 简单介绍 可重入读写锁时基于AQS实现的,典型的用法如JDK1.7中的演示样例: class RWDictionary { private ...

随机推荐

  1. 使用Docker测试静态网站

    参考书籍 :第一本docker书[澳]James Turnbull  1.Sample网站的初始Dockerfile 文件目录如下: Dockerfile文件代码: 安装nginx 在容器中创建一个目 ...

  2. MD5、公钥、私钥、加密、认证

    MD5 MD5的全称是Message-Digest Algorithm 5. MD5将任意长度的“字节串”变换成一个128bit的大整数,并且它是一个不可逆的字符串变换算法. 换句话说就是,即使你看到 ...

  3. windows下安装ssdb

    官方下载 http://ssdb.io/docs/install.html 这是官方网站 官方建议 Do not run SSDB server on Windows system for a pro ...

  4. 【CSS】323- 深度解析 CSS 中的“浮动”

    对于浮动这篇文章解析的狠透彻 ~ 写在最前 习惯性去谷歌翻译看了看 float 的解释: 其中有一句这样写的: she relaxed, floating gently in the water 瞬间 ...

  5. httpBasic 认证的URL访问

    httpBasic 认证 要在发送请求的时候添加HTTP Basic Authentication认证信息到请求中,有两种方法: 1.在请求头中添加Authorization: Authorizati ...

  6. JavaEE基础(05):过滤器、监听器、拦截器,应用详解

    本文源码:GitHub·点这里 || GitEE·点这里 一.Listener监听器 1.概念简介 JavaWeb三大组件:Servlet,Listener,Filter.监听器就是指在应用程序中监听 ...

  7. CSS之position属性

    层级的话可以用z-inde进行设置

  8. JS基础-this

    this this的指向有哪几种情况? this代表函数调用相关联的对象,通常页称之为执行上下文. 作为函数直接调用,非严格模式下,this指向window,严格模式下,this指向undefined ...

  9. 计算机二级Python

    概述 计算机二级在近两年新加了python的选择,趁机考了一下,顺便记录一下学习的一些所获 第一章 程序设计语言概述 考纲考点: 这一部分主要是介绍计算机语言的公共常识,一些尝试我就按照自己的理解方式 ...

  10. Chrome浏览器字体设置低于12px无效

    在Chrome 在IE11                 本来以为是padding问题导致出现左右两边的底部不在同一直线(在IE上),在Chrome显示是正常的,查了一下,IE11和Chrome都是 ...