概述
我们这里共享锁已ReentrantReadWriteLock读写锁为例来进行说明,写锁是排它锁,读锁是共享锁,如下图
图一,当t1线程获取了读锁后,t2线程也是可以获取到读锁,但是当t3线程获取写锁时,则对写锁进行阻塞。
图二,当t1线程获取到写锁后,t2、t3是没法获取读锁的
下面让我们分析一下读锁的是怎么实现的
ReentrantReadWriteLock共享锁实现分析
实现共享锁主要要实现两个方法,如下
获取锁实现方法
更改state的值返回大于等于0的值,则获取成功,否则获取失败,线程进入sync队列进行阻塞
protected int tryAcquireShared(int arg) {throw new UnsupportedOperationException();}
释放锁的方法
更改state状态,更新成功返回true,否则返回false
protected boolean tryReleaseShared(int arg) {throw new UnsupportedOperationException();}
精简了ReentrantReadWriteLock的读锁部分代码,看核心方法是怎么实现共享锁的
public static class ReadLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -5992448646407690164L;
private final Sync sync;
...
protected ReadLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
public void lock() {
sync.acquireShared(1);
}
public void unlock() {
sync.releaseShared(1);
}
...
}
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 6317671515068378041L;
Sync() {
readHolds = new ThreadLocalHoldCounter();
setState(getState()); // ensures visibility of readHolds
}
/**
*读锁的获取
*/
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)) {
return 1;
}
return fullTryAcquireShared(current);
}
/**
*循环尝试获取读锁
**/
final int fullTryAcquireShared(Thread current) {
for (;;) {
int c = getState();
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)
return -1;
} else if (readerShouldBlock()){
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
if (compareAndSetState(c, c + SHARED_UNIT)) {
...
return 1;
}
}
}
}
/**
*读锁的释放
**/
protected final boolean tryReleaseShared(int unused) {
for (;;) {
int c = getState();
int nextc = c - SHARED_UNIT;
if (compareAndSetState(c, nextc))
return nextc == 0;
}
}
}
readlock的tryAcquireShared获取
- 如果有写锁,并且写线程不等于当前线程则返回-1
- 如果队列中没有读锁排队并且读次数没有超过最大次数,则进行更改state值(state高位16位+1,因为state一个变量要表示读写两种状态,所以进行切分,高位16位表示读,低位16表示写),如果更改成功则返回1;
- 如果第二步不满足条件,则进入fullTryAcquireShared方法,循环调用,因为在第二步多个线程获取读锁时,更改state值时有可能失败。
readlock的tryReleaseShared的释放
- state-1,如果更改失败,循环重试,更改成功并且state的值为0,则返回true
可以看到继承AQS实现一个共享锁还是很简单,下面分析AQS共享锁的实现。
AQS共享锁实现
共享锁获取
public final void acquireShared(int arg) {
if (tryAcquireShared(arg) < 0)
doAcquireShared(arg);
}
private void doAcquireShared(int arg) {
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
boolean interrupted = false;
for (;;) {
final Node p = node.predecessor();
if (p == head) {
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
if (interrupted)
selfInterrupt();
failed = false;
return;
}
}
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
private void setHeadAndPropagate(Node node, int propagate) {
Node h = head; // Record old head for check below
setHead(node);
if (propagate > 0 || h == null || h.waitStatus < 0 ||
(h = head) == null || h.waitStatus < 0) {
Node s = node.next;
//这里节点==null,不太理解,理论上不应该next为null。
if (s == null || s.isShared())
doReleaseShared();
}
}
-
调用tryAcquireShared尝试获取锁,如果返回大于等于0时,表示能够获取锁。而此方法也是需要子类必须实现的方法。
-
如果返回小于0,则进行doAcquireShared,自旋获取锁,(这里注意下addWaiter(Node.SHARED)的方法,节点类型为SHARED)
-
如果当前节点前驱节点为头结点,则进行再次调用tryAcquireShared方法获取锁。
4. 如果获取成功,则修改头结点为当前节点,并唤醒后续节点类型为SHARED节点。
5. 如果获取失败,则修改状态waitstatus=SIGNAL,进行休眠,等待唤醒。 -
如果对当前进行了中断,则调用cancelAcquire方法,进行node节点顺序变更。
共享锁释放
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
private void doReleaseShared() {
for (;;) {
Node h = head;
if (h != null && h != tail) {
int ws = h.waitStatus;
if (ws == Node.SIGNAL) {
if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
continue; // loop to recheck cases
unparkSuccessor(h);
}
//把waitStatus更改为PROPAGATE,感觉没啥意义?
else if (ws == 0 &&
!compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
continue; // loop on failed CAS
}
if (h == head) // loop if head changed
break;
}
}
- 调用tryReleaseShared更改state值,如果state值等于0,则返回true,则调用doReleaseShared更改sync队列的头部节点waitStatus为0,并调用unpack唤醒sync头部节点。
疑问
- 把waitStatus更改为PROPAGATE,没怎么理解,懂得同学,可以留言一起讨论下。