公平锁与非公平锁的关键区别
所属分类 java
浏览量 1306
java8
公平锁 按排队顺序获取锁
公平锁:老的线程排队使用锁,新线程仍然排队使用锁。
非公平锁:老的线程排队使用锁;但是无法保证新线程抢占已经在排队的线程的锁。
hasQueuedPredecessors
Queries whether any threads have been waiting to acquire longer than the current thread.
!hasQueuedPredecessors() 保证 新的线程和已经排队的线程都顺序使用锁
public class ReentrantLock implements Lock
static final class NonfairSync extends Sync
static final class FairSync extends Sync
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
公平锁
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;
}
非公平锁
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;
}
公平锁增加了 hasQueuedPredecessors()判断
public final boolean hasQueuedPredecessors() {
// The correctness of this depends on head being initialized
// before tail and on head.next being accurate if the current
// thread is first in queue.
Node t = tail; // Read fields in reverse initialization order
Node h = head;
Node s;
return h != t &&
((s = h.next) == null || s.thread != Thread.currentThread());
}
Queries whether any threads have been waiting to acquire longer than the current thread.
An invocation of this method is equivalent to (but may be more efficient than):
getFirstQueuedThread() != Thread.currentThread() && hasQueuedThreads()
predecessors 前任
上一篇
下一篇
btrace使用简介
为什么开发一个操作系统那么难
AQS同步队列与条件队列
自定义注解实例
springboot应用jar包冲突解决实例
eclipse中分析pom文件