公平鎖與非公平鎖
簡單說一下兩個鎖的區別:
顧名思義,公平就是先到先得,比如A和B線程均需要獲得一個鎖,但是此時鎖正在被另一個線程C佔據着,這是如果A先來B後來。那麼當C釋放鎖以後,A就會獲得這個鎖。
如果是非公平的話,可能B後來但是能比A先獲得鎖。
ReentrantLock可以設置鎖的屬性爲公平還是非公平
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
public ReentrantLock() {
sync = new NonfairSync();
}
默認無參構造創建的是非公平鎖,這樣做的好處就是能夠提高性能。至於爲什麼非公平鎖能提高性能,我們等下分析源碼解釋。
直接上兩種鎖 獲取鎖的源碼
先公平鎖
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;
/**
* Fair version of tryAcquire. Don't grant access unless
* recursive call or no waiters or is first.
*/
@ReservedStackAccess
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); //更新state值
return true;
}
return false;
}
}
c表示當前線程的狀態。
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());
}
公平鎖獲取鎖的條件是是否有等待隊列,有的話就嘗試獲取鎖。非公平鎖
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;
}
release釋放鎖
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);
}
setState(c);
return free;
}
lock()
public void lock() {
sync.acquire(1);
}
線程每次調用lock方法,如果成功獲取的話,state值就會加1。
當一個線程獲取到了鎖之後state值在每次一獲取和釋放鎖之後會更新,只有當state值爲0時,別的線程纔有可能獲取到這個鎖,進而執行自己線程的任務。