读书人

懂得ReentrantReadWriteLock

发布时间: 2012-11-26 11:48:49 作者: rapoo

理解ReentrantReadWriteLock

本文主要内容是对并发包中的读写锁的认识,主要解释读写锁的请求过程,锁降级的实现以及锁升级的不可能性。

?

首先来了解一些常量和简单方法,贴下代码

/** * Full version of acquire for reads, that handles CAS misses * and reentrant reads not dealt with in tryAcquireShared. */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 = cachedHoldCounter;    if (rh == null || rh.tid != current.getId())        rh = readHolds.get();    for (;;) {        int c = getState();        int w = exclusiveCount(c);        if ((w != 0 && getExclusiveOwnerThread() != current) ||            ((rh.count | w) == 0 && readerShouldBlock(current)))            return -1; //标记2        if (sharedCount(c) == MAX_COUNT)            throw new Error("Maximum lock count exceeded");        if (compareAndSetState(c, c + SHARED_UNIT)) {            cachedHoldCounter = rh; // cache for release            rh.count++;            return 1;        }    }}

它在标记2处返回-1,表示读线程获取锁失败,将进入同步队列。所以从读取锁升级写入锁是不可能的。

?

最后就是锁的释放,在理解了本文,相信看读写锁的释放操作还是比较简单的。

?

?

?

读书人网 >开源软件

热点推荐