ReentrantReadWriteLock笔记

构造的时候
public ReentrantReadWriteLock( boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock( this );
writerLock = new WriteLock( this );
}

调用读锁
reentrantReadWriteLock.readLock().tryLock();
//读锁的 sync就是 ReentrantReadWriteLock的 sync

public boolean tryLock() {
return sync .tryReadLock();
}
//进入 tryReadLock
final boolean tryReadLock() {
Thread current = Thread. currentThread ();
for (;;) {
//state 分为 65535 的两份,包括重入和新的线程 , 一个读锁就是 65536, 一个写锁就是 1
int c = getState();
//这个里面c&(1<<16-1)就是看看写锁占用了没,占了又不是当前线程就失败
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 ;
}
}
}


然后看看 reentrantReadWriteLock.readLock().lock();
//进来
public void lock() {
sync .acquireShared( 1 );
}
再进来 acquireShared
public final void acquireShared( int arg) {
if (tryAcquireShared(arg) < 0 )
doAcquireShared(arg);
}

//先进去 tryAcquireShared看看

protected final int tryAcquireShared( int unused) {

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 ;
}
// 读取的完整版本,处理CAS丢失和重入读不处理的tryAcquireShared。
return fullTryAcquireShared(current);
}


进入 fullTryAcquireShared看看,这边也就是试试看不成功就返回代码都差不多
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 ;
}
}
}

运行完了再返回到
public final void acquireShared( int arg) {
if (tryAcquireShared(arg) < 0 )
doAcquireShared(arg);
}

进入 doAcquireShared
private void doAcquireShared( int arg) {
//加入等待队列和 Reentrant锁一样的代码
final Node node = addWaiter(Node. SHARED );
boolean failed = true ;
try {
boolean interrupted = false ;
for (;;) {
final Node p = node.predecessor();
if (p == head ) {
//当前一个为head的时候尝试获取锁
int r = tryAcquireShared(arg);
if (r >= 0 ) {
setHeadAndPropagate(node, r);
p. next = null ; // help GC
//如果线程中断修改中断位
if (interrupted)
selfInterrupt ();
failed = false ;
return ;
}
}
//这个和 Reentrant锁一样 AbstractQueuedSynchronizer的方法
if ( shouldParkAfterFailedAcquire (p, node) &&
parkAndCheckInterrupt())
interrupted = true ;
}
} finally {
if (failed)
cancelAcquire(node);
}
}


看看释放锁吧
public void unlock() {
sync .release( 1 );
}

进入 release里面看看
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
protected final boolean tryRelease( int releases) {
//判断占有的线程是否是现在进来释放的
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
//线程数减1
int nextc = getState() - releases;
//看看线程是不是放完了
boolean free = exclusiveCount (nextc) == 0 ;
//放完了就把当前占用线程设置为空
if (free)
setExclusiveOwnerThread( null );
//设置占用数
setState(nextc);
return free;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值