java學習之ReentrantLock
本篇博文主要記錄ReentranctLock內部實現原理。
ReentrantLock和Synchronized關鍵字相比,使用起來比較靈活。如何使用ReentranctLock就不多講了,這裏主要記錄ReentrantLock的內部實現原理。
首先看下ReentrantLock的類繼承結構, 如下圖:
ReentrantLock內部有三個內部類: Sync, FairSync, NonfairSync. 源碼如下:
Sync:
abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -5179523762034025860L; /** * Performs {@link Lock#lock}. The main reason for subclassing * is to allow fast path for nonfair version. */ abstract void lock(); /** * Performs non-fair tryLock. tryAcquire is implemented in * subclasses, but both need nonfair try for trylock method. */ 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; } 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; }
... }
FairSync:
static final class FairSync extends Sync { private static final long serialVersionUID = -3000897897090466540L; final void lock() { acquire(1); } /** * Fair version of tryAcquire. Don‘t grant access unless * recursive call or no waiters or is first. */ 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; } }
NonfairSync:
static final class NonfairSync extends Sync { private static final long serialVersionUID = 7316153563782823691L; /** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ final void lock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } protected final boolean tryAcquire(int acquires) { return nonfairTryAcquire(acquires); } }
FairSync實現了公平鎖邏輯, NonfairSync實現的是非公平鎖的邏輯。 下面看下最常使用的非公平鎖的實現。
NonfairSync.lock()方法,首先基於CAS設置AQS中的state,如果返回true, 說明獲取成功,此時將排他線程設置為當前線程。如果返回false, 說明獲取失敗,調用acquire(1)方法。acquire()方法在AQS中,代碼如下:
public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); }
在acquire中首先再次獲取鎖, 如果獲取失敗, 則調用addWaiter()方法,將當前線程加入CHL隊列。CHL隊列結構如下:
加入隊列後,然後調用方法acquireQueued(), 代碼如下:
final boolean acquireQueued(final Node node, int arg) { boolean failed = true; try { boolean interrupted = false; for (;;) { final Node p = node.predecessor(); if (p == head && tryAcquire(arg)) { setHead(node); p.next = null; // help GC failed = false; return interrupted; } if (shouldParkAfterFailedAcquire(p, node) && parkAndCheckInterrupt()) interrupted = true; } } finally { if (failed) cancelAcquire(node); } }
在acquireQueued()方法中,首先判斷當前節點的前置節點是不是頭結點,如果是頭結點,則嘗試獲取鎖,獲取成功,則當前節點設置為頭結點。否則判斷是否應該講當前節點對應的線程掛起, 如果前一個前一個節點的status是SIGNAL, 則說明需要將當前節點掛起。調用parkAndCheckInterrupt()方法掛起當前節點的線程。
上面是非公平鎖的lock()邏輯,公平鎖和非公平鎖的,區別主要是公平鎖在獲取之前,首先需要判斷是否存在前置節點,如果存在前置節點,則需要等待。我們看到FairSync中的tryAcquire()方法中,首先調用了hasQueuedPredecessors()方法,判斷是否存在前置節點。
java學習之ReentrantLock