- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Java 读写锁实现原理浅析由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
最近做的一个小项目中有这样的需求:整个项目有一份config.json保存着项目的一些配置,是存储在本地文件的一个资源,并且应用中存在读写(读>>写)更新问题。既然读写并发操作,那么就涉及到操作互斥,这里自然想到了读写锁,本文对读写锁方面的知识做个梳理.
为什么需要读写锁?
与传统锁不同的是读写锁的规则是可以共享读,但只能一个写,总结起来为:读读不互斥,读写互斥,写写互斥,而一般的独占锁是:读读互斥,读写互斥,写写互斥,而场景中往往读远远大于写,读写锁就是为了这种优化而创建出来的一种机制.
注意是读远远大于写,一般情况下独占锁的效率低来源于高并发下对临界区的激烈竞争导致线程上下文切换。因此当并发不是很高的情况下,读写锁由于需要额外维护读锁的状态,可能还不如独占锁的效率高。因此需要根据实际情况选择使用.
一个简单的读写锁实现 。
根据上面理论可以利用两个int变量来简单实现一个读写锁,实现虽然烂,但是原理都是差不多的,值得阅读下.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
public
class
readwritelock {
/**
* 读锁持有个数
*/
private
int
readcount =
0
;
/**
* 写锁持有个数
*/
private
int
writecount =
0
;
/**
* 获取读锁,读锁在写锁不存在的时候才能获取
*/
public
synchronized
void
lockread()
throws
interruptedexception {
// 写锁存在,需要wait
while
(writecount >
0
) {
wait();
}
readcount++;
}
/**
* 释放读锁
*/
public
synchronized
void
unlockread() {
readcount--;
notifyall();
}
/**
* 获取写锁,当读锁存在时需要wait.
*/
public
synchronized
void
lockwrite()
throws
interruptedexception {
// 先判断是否有写请求
while
(writecount >
0
) {
wait();
}
// 此时已经不存在获取写锁的线程了,因此占坑,防止写锁饥饿
writecount++;
// 读锁为0时获取写锁
while
(readcount >
0
) {
wait();
}
}
/**
* 释放读锁
*/
public
synchronized
void
unlockwrite() {
writecount--;
notifyall();
}
}
|
readwritelock的实现原理 。
在java中readwritelock的主要实现为reentrantreadwritelock,其提供了以下特性:
reentrantreadwritelock的结构 。
reentrantreadwritelock的核心是由一个基于aqs的同步器sync构成,然后由其扩展出readlock(共享锁),writelock(排它锁)所组成.
并且从reentrantreadwritelock的构造函数中可以发现readlock与writelock使用的是同一个sync,具体怎么实现同一个队列既可以为共享锁,又可以表示排他锁下文会具体分析.
清单一:reentrantreadwritelock构造函数 。
1
2
3
4
5
|
public
reentrantreadwritelock(
boolean
fair) {
sync = fair ?
new
fairsync() :
new
nonfairsync();
readerlock =
new
readlock(
this
);
writerlock =
new
writelock(
this
);
}
|
sync的实现 。
sync是读写锁实现的核心,sync是基于aqs实现的,在aqs中核心是state字段和双端队列,那么一个一个问题来分析.
sync如何同时表示读锁与写锁?
清单2:读写锁状态获取 。
1
2
3
4
5
6
7
8
|
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; }
|
从代码中获取读写状态可以看出其是把state(int32位)字段分成高16位与低16位,其中高16位表示读锁个数,低16位表示写锁个数,如下图所示(图来自java并发编程艺术).
该图表示当前一个线程获取到了写锁,并且重入了两次,因此低16位是3,并且该线程又获取了读锁,并且重入了一次,所以高16位是2,当写锁被获取时如果读锁不为0那么读锁一定是获取写锁的这个线程.
读锁的获取 。
读锁的获取主要实现是aqs中的acquireshared方法,其调用过程如下代码.
清单3:读锁获取入口 。
1
2
3
4
5
6
7
8
9
|
// readlock
public
void
lock() {
sync.acquireshared(
1
);
}
// aqs
public
final
void
acquireshared(
int
arg) {
if
(tryacquireshared(arg) <
0
)
doacquireshared(arg);
}
|
其中doacquireshared(arg)方法是获取失败之后aqs中入队操作,等待被唤醒后重新获取,那么关键点就是tryacquireshared(arg)方法,方法有点长,因此先总结出获取读锁所经历的步骤,获取的第一部分步骤如下:
清单4:读锁获取的第一部分 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
protected
final
int
tryacquireshared(
int
unused) {
thread current = thread.currentthread();
int
c = getstate();
// 操作1:存在写锁,并且写锁不是当前线程则直接去排队
if
(exclusivecount(c) !=
0
&&
getexclusiveownerthread() != current)
return
-
1
;
int
r = sharedcount(c);
// 操作2:读锁是否该阻塞,对于非公平模式下写锁获取优先级会高,如果存在要获取写锁的线程则读锁需要让步,公平模式下则先来先到
if
(!readershouldblock() &&
// 读锁使用高16位,因此存在获取上限为2^16-1
r < max_count &&
// 操作3:cas修改读锁状态,实际上是读锁状态+1
compareandsetstate(c, c + shared_unit)) {
// 操作4:执行到这里说明读锁已经获取成功,因此需要记录线程状态。
if
(r ==
0
) {
firstreader = current;
// firstreader是把读锁状态从0变成1的那个线程
firstreaderholdcount =
1
;
}
else
if
(firstreader == current) {
firstreaderholdcount++;
}
else
{
// 这些代码实际上是从threadlocal中获取当前线程重入读锁的次数,然后自增下。
holdcounter rh = cachedholdcounter;
// cachedholdcounter是上一个获取锁成功的线程
if
(rh ==
null
|| rh.tid != getthreadid(current))
cachedholdcounter = rh = readholds.get();
else
if
(rh.count ==
0
)
readholds.set(rh);
rh.count++;
}
return
1
;
}
// 当操作2,操作3失败时执行该逻辑
return
fulltryacquireshared(current);
}
|
当操作2,操作3失败时会执行fulltryacquireshared(current),为什么会这样写呢?个人认为是一种补偿操作,操作2与操作3失败并不代表当前线程没有读锁的资格,并且这里的读锁是共享锁,有资格就应该被获取成功,因此给予补偿获取读锁的操作。在fulltryacquireshared(current)中是一个循环获取读锁的过程,大致步骤如下:
清单5:读锁获取的第二部分 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
final
int
fulltryacquireshared(thread current) {
holdcounter rh =
null
;
// 最外层嵌套循环
for
(;;) {
int
c = getstate();
// 操作5:存在写锁,且写锁并非当前线程则直接返回失败
if
(exclusivecount(c) !=
0
) {
if
(getexclusiveownerthread() != current)
return
-
1
;
// else we hold the exclusive lock; blocking here
// would cause deadlock.
// 操作6:如果当前线程是重入读锁则放行
}
else
if
(readershouldblock()) {
// make sure we're not acquiring read lock reentrantly
// 当前是firstreader,则直接放行,说明是已获取的线程重入读锁
if
(firstreader == current) {
// assert firstreaderholdcount > 0;
}
else
{
// 执行到这里说明是其他线程,如果是cachedholdcounter(其count不为0)也就是上一个获取锁的线程则可以重入,否则进入aqs中排队
// **这里也是对写锁的让步**,如果队列中头结点为写锁,那么当前获取读锁的线程要进入队列中排队
if
(rh ==
null
) {
rh = cachedholdcounter;
if
(rh ==
null
|| rh.tid != getthreadid(current)) {
rh = readholds.get();
if
(rh.count ==
0
)
readholds.remove();
}
}
// 说明是上述刚初始化的rh,所以直接去aqs中排队
if
(rh.count ==
0
)
return
-
1
;
}
}
if
(sharedcount(c) == max_count)
throw
new
error(
"maximum lock count exceeded"
);
// 操作7:修改读锁状态,实际上读锁自增操作
if
(compareandsetstate(c, c + shared_unit)) {
// 操作8:对threadlocal中维护的获取锁次数进行更新。
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
;
}
}
}
|
读锁的释放 。
清单6:读锁释放入口 。
1
2
3
4
5
6
7
8
9
10
11
12
|
// readlock
public
void
unlock() {
sync.releaseshared(
1
);
}
// sync
public
final
boolean
releaseshared(
int
arg) {
if
(tryreleaseshared(arg)) {
doreleaseshared();
// 这里实际上是释放读锁后唤醒写锁的线程操作
return
true
;
}
return
false
;
}
|
读锁的释放主要是tryreleaseshared(arg)函数,因此拆解其步骤如下:
清单7:读锁的释放流程 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
protected
final
boolean
tryreleaseshared(
int
unused) {
thread current = thread.currentthread();
// 操作1:清理threadlocal对应的信息
if
(firstreader == current) {;
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;
}
// 操作2:循环中利用cas修改读锁状态
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
;
}
}
|
写锁的获取 。
清单8:写锁的获取入口 。
1
2
3
4
5
6
7
8
9
10
11
|
// writelock
public
void
lock() {
sync.acquire(
1
);
}
// aqs
public
final
void
acquire(
int
arg) {
// 尝试获取,获取失败后入队,入队失败则interrupt当前线程
if
(!tryacquire(arg) &&
acquirequeued(addwaiter(node.exclusive), arg))
selfinterrupt();
}
|
写锁的获取也主要是tryacquire(arg)方法,这里也拆解步骤:
清单9:写锁的获取 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
protected
final
boolean
tryacquire(
int
acquires) {
thread current = thread.currentthread();
int
c = getstate();
int
w = exclusivecount(c);
// 操作1:c != 0,说明存在读锁或者写锁
if
(c !=
0
) {
// (note: if c != 0 and w == 0 then shared count != 0)
// 写锁为0,读锁不为0 或者获取写锁的线程并不是当前线程,直接失败
if
(w ==
0
|| current != getexclusiveownerthread())
return
false
;
if
(w + exclusivecount(acquires) > max_count)
throw
new
error(
"maximum lock count exceeded"
);
// reentrant acquire
// 执行到这里说明是写锁线程的重入操作,直接修改状态,也不需要cas因为没有竞争
setstate(c + acquires);
return
true
;
}
// 操作2:获取写锁,writershouldblock对于非公平模式直接返回fasle,对于公平模式则线程需要排队,因此需要阻塞。
if
(writershouldblock() ||
!compareandsetstate(c, c + acquires))
return
false
;
setexclusiveownerthread(current);
return
true
;
}
|
写锁的释放 。
清单10:写锁的释放入口 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
// writelock
public
void
unlock() {
sync.release(
1
);
}
// aqs
public
final
boolean
release(
int
arg) {
// 释放锁成功后唤醒队列中第一个线程
if
(tryrelease(arg)) {
node h = head;
if
(h !=
null
&& h.waitstatus !=
0
)
unparksuccessor(h);
return
true
;
}
return
false
;
}
|
写锁的释放主要是tryrelease(arg)方法,其逻辑就比较简单了,注释很详细.
清单11:写锁的释放 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
protected
final
boolean
tryrelease(
int
releases) {
// 如果当前线程没有获取写锁却释放,则直接抛异常
if
(!isheldexclusively())
throw
new
illegalmonitorstateexception();
// 状态变更至nextc
int
nextc = getstate() - releases;
// 因为写锁是可以重入,所以在都释放完毕后要把独占标识清空
boolean
free = exclusivecount(nextc) ==
0
;
if
(free)
setexclusiveownerthread(
null
);
// 修改状态
setstate(nextc);
return
free;
}
|
一些其他问题 。
锁降级操作哪里体现?
锁降级操作指的是一个线程获取写锁之后再获取读锁,然后读锁释放掉写锁的过程。在tryacquireshared(arg)获取读锁的代码中有如下代码.
清单12:写锁降级策略 。
1
2
3
4
5
6
7
|
thread current = thread.currentthread();
// 当前状态
int
c = getstate();
// 存在写锁,并且写锁不等于当前线程时返回,换句话说等写锁为当前线程时则可以继续往下获取读锁。
if
(exclusivecount(c) !=
0
&&
getexclusiveownerthread() != current)
return
-
1
;
|
。。。。。读锁获取。。。。.
那么锁降级有什么用?答案是为了可见性的保证。在reentrantreadwritelock的javadoc中有如下代码,其是锁降级的一个应用示例.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
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
// 这里再次获取读锁,如果不获取那么当写锁释放后可能其他写线程再次获得写锁,导致下方`use(data)`时出现不一致的现象
// 这个操作就是降级
rwl.readlock().lock();
}
finally
{
rwl.writelock().unlock();
// unlock write, still hold read
}
}
try
{
// 使用完后释放读锁
use(data);
}
finally
{
rwl.readlock().unlock();
}
}
}}
|
公平与非公平的区别 。
清单13:公平下的sync 。
1
2
3
4
5
6
7
8
9
|
static
final
class
fairsync
extends
sync {
private
static
final
long
serialversionuid = -2274990926593161451l;
final
boolean
writershouldblock() {
return
hasqueuedpredecessors();
// 队列中是否有元素,有责当前操作需要block
}
final
boolean
readershouldblock() {
return
hasqueuedpredecessors();
// 队列中是否有元素,有责当前操作需要block
}
}
|
公平下的sync实现策略是所有获取的读锁或者写锁的线程都需要入队排队,按照顺序依次去尝试获取锁.
清单14:非公平下的sync 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
static
final
class
nonfairsync
extends
sync {
private
static
final
long
serialversionuid = -8159625535654395037l;
final
boolean
writershouldblock() {
// 非公平下不考虑排队,因此写锁可以竞争获取
return
false
;
// writers can always barge
}
final
boolean
readershouldblock() {
/* 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 probabilistic 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();
}
}
|
非公平下由于抢占式获取锁,写锁是可能产生饥饿,因此解决办法就是提高写锁的优先级,换句话说获取写锁之前先占坑.
总结 。
以上所述是小编给大家介绍的java 读写锁实现原理浅析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我网站的支持! 。
原文链接:https://my.oschina.net/editorial-story/blog/1928306 。
最后此篇关于Java 读写锁实现原理浅析的文章就讲到这里了,如果你想了解更多关于Java 读写锁实现原理浅析的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
一、公平锁和非公平锁 1.1、公平锁和非公平锁的概述 公平锁:指多个线程按照申请锁的顺序来获取锁。 非公平锁:指在多线程获取锁的顺序并不是按照申请锁的顺序,有可能后申请的线程比先申请的线程优先获取到锁
阅读目录 1、简介 2、分类 3、全局锁 4、表级锁 5、表锁 6、元数据锁
因此,在我编写的程序中,我有三个函数,为了简单起见,我们将它们称为 A、B 和 C。每个函数都需要访问资源X才能工作。 限制是A和B不允许同时运行并且必须适当同步。但是,C 可以与 A 或 B 同时运
我听说过这些与并发编程相关的词,但是锁、互斥量和信号量之间有什么区别? 最佳答案 锁只允许一个线程进入被锁定的部分,并且该锁不与任何其他进程共享。 互斥锁与锁相同,但它可以是系统范围的(由多个进程共享
这个问题已经有答案了: What is an efficient way to implement a singleton pattern in Java? [closed] (29 个回答) 已关闭
这个问题已经有答案了: What is an efficient way to implement a singleton pattern in Java? [closed] (29 个回答) 已关闭
我对标题中的主题有几个问题。首先,假设我们使用 JDBC,并且有 2 个事务 T1 和 T2。在 T1 中,我们在一个特定的行上执行 select 语句。然后我们对该行执行更新。在事务 T2 中,我们
我希望我的函数只运行一次。这意味着如果多个线程同时调用它,该函数将阻塞所有线程,只允许它运行。 最佳答案 听起来您希望存储过程进行同步。为什么不直接将同步放在应用程序本身中。 pthread_mute
if (runInDemoMode) { lock (this) { //Initalization of tables dCreator.create
我相信无论使用什么语言都可以考虑我的问题,但是为了有一些“ anchor ”,我将使用 Java 语言来描述它。 让我们考虑以下场景:我有一个扩展 Thread 的类 PickyHost 及其实例 p
我知道异步不是并行的,但我现在遇到了一个非常有趣的情况。 async function magic(){ /* some processing here */ await async () =
我们正在使用 Scala、Play 框架和 MongoDB(以 ReactiveMongo 作为我们的驱动程序)构建一个网络应用程序。应用程序架构是端到端的非阻塞。 在我们代码的某些部分,我们需要访问
我需要一个简单的锁,JavaME 超时(concurrent.lock 的反向移植需要完整的 Java 1.3)。 如果其他人已经为 JavaME 发布了经过测试的锁定代码,我宁愿使用它。 锁定是出了
根据 boost : To access the object, a weak_ptr can be converted to a shared_ptr using the shared_ptr co
关于 Mutex 和 Critical 部分之间的区别存在一个问题,但它也不处理 Locks。 所以我想知道临界区是否可以用于进程之间的线程同步。 还有信号状态和非信号状态的含义 最佳答案 在 Win
锁 最为常见的应用就是 高并发的情况下,库存的控制。本次只做简单的单机锁介绍。 直接看代码: 每请求一次库存-1. 假如库存1000,在1000个人请求之后,库存将变为0。
线程和进程 1、线程共享创建它的进程的地址空间,进程有自己的地址空间 2、线程可以访问进程所有的数据,线程可以相互访问 3、线程之间的数据是独立的 4、子进程复制线程的数据 5、子进程启动
**摘要:**细心的你也一定关注到,有的网址是https开头的,有的是http。https开头的网站前面,会有一把小锁。这是为什么呢? 本文分享自华为云社区《还不知道SSL证书已经是刚需了?赶快来了解
试图在 C 中实现一个非常简单的互斥锁(锁)我有点困惑。我知道互斥锁类似于二进制信号量,除了互斥锁还强制执行释放锁的线程的约束,必须是最近获得它的同一线程。我对如何跟踪所有权感到困惑? 这是我到目前为
在阅读了很多与上述主题相关的文章和答案之后,我仍然想知道 SQL Server 数据库引擎在以下示例中是如何工作的: 假设我们有一个名为 t3 的表: create table t3 (a int ,
我是一名优秀的程序员,十分优秀!