java writelock 问题_Java ReentrantWriteLock 同个线程先获取读锁,不能再获取写锁

问题描述

ReentrantWriteLock 同个线程首先获取写锁后可以接着获取读锁(锁降级)以及写锁,但是获取读锁后就只能获取读锁,这个是出于什么考虑?

相关代码

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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值