偏心锁与非偏心锁是指,多个线程在获取同一把锁的策略,是依照先到先得还是间接竞争。先到先得的策略就是偏心锁,排队对所有的线程来说是偏心的,间接竞争的策略则是非偏心的。
在调用ReenterantLock的构造函数的时候决定是结构一个偏心锁还是非偏心锁。
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
来看获取锁的过程:
ReentrantLock lock = new ReentrantLock();
lock.lock();
点进去看,是调用了sync的lock办法
这里就是对应了咱们的偏心锁/非偏心锁的lock办法。
到这里没有什么大的差别,无非是非偏心锁多了一个步骤。cas操作去尝试获取锁,胜利了设置owner线程为以后线程。失败了再调用acquire办法获取锁。
那接下来持续看两种锁的acquire办法,两个办法都来到了aqs的acquire办法。
点进去那些办法,所有办法都进入了aqs实现的步骤,只有tryAcquire办法有不同的实现。
进去看,偏心锁只是多了 hasQueuedPredecessors
这个办法。
偏心锁
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) { // 以后锁的状态是无所状态
if (!hasQueuedPredecessors() && // 判断队列中是否有前驱节点,若果有前驱节点,就不会执行上面的代码,不会去获取锁
compareAndSetState(0, acquires)) { // 应用cas尝试获取锁
setExclusiveOwnerThread(current); // 设置owner线程为以后线程
return true;
}
}
else if (current == getExclusiveOwnerThread()) { // 持有锁的线程为以后线程
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc); // 更新sate(重入锁的原理)
return true;
}
return false;
}
以上剖析了偏心锁和非偏心锁的一个不同。
上面以非偏心锁剖析加锁的过程
获取锁的过程:
/**
* Performs lock. Try immediate barge, backing up to normal * acquire on failure. */final void lock() {
if (compareAndSetState(0, 1)) // 尝试用cas来获取锁(扭转state的值)
setExclusiveOwnerThread(Thread.currentThread()); // 设置owner线程为以后线程
else
acquire(1); // 如果锁的状态不为0,被其余线程持有,尝试获取锁
}
public final void acquire(int arg) {
if (!tryAcquire(arg) &&
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
selfInterrupt();
}
tryAcquire(arg)办法是尝试获取锁。
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;
}
原理和下面偏心锁的tryAcquire办法统一。
acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
办法:
addWaiter办法:
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node);
return node;
}
创立一个node,入队,并返回该NodeacquireQueued
再尝试获取锁
非偏心锁解锁的过程:
public final boolean release(int arg) {
if (tryRelease(arg)) { // 尝试去开释锁
Node h = head;
if (h != null && h.waitStatus != 0) // h头结点为空,并且state不等于0
unparkSuccessor(h); // 去唤醒后继节点
return true;
}
return false;
}
protected final boolean tryRelease(int releases) {
int c = getState() - releases;
if (Thread.currentThread() != getExclusiveOwnerThread())
throw new IllegalMonitorStateException();
boolean free = false;
if (c == 0) {
free = true;
setExclusiveOwnerThread(null); // 设置owner线程为空
}
setState(c); // 更新state
return free;
}
发表回复