基于 AbstractQueuedSynchronizer 的并发类实现
Posted 张宏杰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于 AbstractQueuedSynchronizer 的并发类实现相关的知识,希望对你有一定的参考价值。
公平模式ReentrantLock实现原理
前面的文章研究了AbstractQueuedSynchronizer的独占锁和共享锁,有了前两篇文章的基础,就可以乘胜追击,看一下基于AbstractQueuedSynchronizer的并发类是如何实现的。
ReentrantLock显然是一种独占锁,首先是公平模式的ReentrantLock,Sync是ReentractLock中的基础类,继承自AbstractQueuedSynchronizer,看一下代码实现:
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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
abstract
static
class
Sync
extends
AbstractQueuedSynchronizer
private
static
final
long
serialVersionUID = -5179523762034025860L;
/**
* Performs @link Lock#lock. The main reason for subclassing
* is to allow fast path for nonfair version.
*/
abstract
void
lock();
/**
* Performs non-fair tryLock. tryAcquire is
* implemented in subclasses, but both need nonfair
* try for trylock method.
*/
final
boolean
nonfairTryAcquire(
int
acquires)
final
Thread current = Thread.currentThread();
int
c = getState();
if
(c ==
0
)
if
(compareAndSetState(
0
, acquires))
setExclusiveOwnerThread(current);
return
true
;
else
if
(current == getExclusiveOwnerThread())
int
nextc = c + acquires;
if
(nextc <
0
)
// overflow
throw
new
Error(
"Maximum lock count exceeded"
);
setState(nextc);
return
true
;
return
false
;
基于内容与基于协作的过滤?
|