公平锁、非公平锁的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;

final void lock() {
acquire(1);
}

// tryAcquire 的公平版本。除非递归调用或没有等待者或者是第一个等待者,否则不要授予访问权限。
protected final boolean tryAcquire(int acquires) {
final Thread current = Thread.currentThread();
int c = getState();
if (c == 0) {
if (!hasQueuedPredecessors() &&
compareAndSetState(0, acquires)) {
setExclusiveOwnerThread(current);
return true;
}
}
else if (current == getExclusiveOwnerThread()) {
int nextc = c + acquires;
if (nextc < 0)
throw new Error("Maximum lock count exceeded");
setState(nextc);
return true;
}
return false;
}
}

public final boolean hasQueuedPredecessors() {
Node t = tail;
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
// 只有 hasQueuedPredecessors 返回 false 才能获取到锁
//
// hasQueuedPredecessors 的意思是:没有排队的前辈
//
// 只有两种情况会获取到锁:
// [获取锁的情况1] 队列中没有节点
// h==t 获取锁
//
// [获取锁的情况2] 队列中有节点,并且队头的下一个 h.next 是当前线程
// h!=t
// h.next != null && h.next.thread == 当前