ReentrantLock與Synchronized區別在于后者是JVM實現,前者是JDK實現,屬于Java對象,使用的時候必須有明確的加鎖(Lock)和解鎖(Release)方法,否則可能會造成死鎖。
先來查看ReentrantLock的繼承關系(下圖),實現了Lock和Serializable接口,表明ReentrantLock對象是可序列化的。
同時在ReentrantLock內部還定義了三個重要的內部類,Sync繼承自抽象類AbstractQueuedSynchronizer(隊列同步器)。其后又分別定義了它的兩個子類公平鎖FairSync和非公平鎖NonfairSync。
/*** Base of synchronization control for this lock. Subclassed* into fair and nonfair versions below. Uses AQS state to* represent the number of holds on the lock.*/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) // overflowthrow 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;}protected final boolean isHeldExclusively() {// While we must in general read state before owner,// we don't need to do so to check if current thread is ownerreturn getExclusiveOwnerThread() == Thread.currentThread();}final ConditionObject newCondition() {return new ConditionObject();}// Methods relayed from outer class final Thread getOwner() {return getState() == 0 ? null : getExclusiveOwnerThread();}final int getHoldCount() {return isHeldExclusively() ? getState() : 0;}final boolean isLocked() {return getState() != 0;}/*** Reconstitutes the instance from a stream (that is, deserializes it).*/private void readObject(java.io.ObjectInputStream s)throws java.io.IOException, ClassNotFoundException {s.defaultReadObject();setState(0); // reset to unlocked state }}/*** Sync object for non-fair locks*/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());elseacquire(1);}protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);}}/*** Sync object for fair locks*/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;}}
然后先看一下ReentrantLock的構造函數:
public ReentrantLock() {sync = new NonfairSync();}/*** Creates an instance of {@code ReentrantLock} with the* given fairness policy.** @param fair {@code true} if this lock should use a fair ordering policy*/public ReentrantLock(boolean fair) {sync = fair ? new FairSync() : new NonfairSync();}
ReentrantLock():無參構造器,默認的是非公平鎖。
ReentrantLock(boolean):有參構造器,根據參數指定公平鎖還是非公平鎖。
從這里可以看出,ReentrantLock其實既可以是公平鎖也可以是非公平鎖,通過參數來進行自定義。
然后我們看一下加鎖方法Lock:
public void lock() {sync.lock();}
內部是調用了構造器中創建的Sync對象,由于默認的是非公平鎖,因此我們先來看一下非公平鎖的實現。
final void lock() {if (compareAndSetState(0, 1))setExclusiveOwnerThread(Thread.currentThread());elseacquire(1);}
從方法名compareAndSetState可以看出這是一個CAS操作,我們點進去查看源碼,這是在AbstractQueuedSynchronized里面定義的一個方法
protected final boolean compareAndSetState(int expect, int update) {// See below for intrinsics setup to support thisreturn unsafe.compareAndSwapInt(this, stateOffset, expect, update);}
通過Unsafe對象來進行CAS操作。由于Unsafe里面定義的是Native方法,通過其他語言實現了對內存的直接操作,因此是保證了線程安全的。
然后我們再來看操作成功后的代碼:setExclusiveOwnerThread(Thread.currentThread());
protected final void setExclusiveOwnerThread(Thread thread) {exclusiveOwnerThread = thread;}
這個方法的實現是在AbstractQueuedSynchronized的父類AbstractOwnableSynchronized中進行的,只是記錄了當前擁有鎖的線程。由于我們在if判斷中已經獲取到了鎖,因此這一步也是線程安全的。由此,非公平鎖獲取結束。
然后我們再看看如果獲取鎖失敗后的執行方法:acquire(1);獲取鎖失敗,則說明現在已經有其他線程獲取到了鎖,并且正在執行代碼塊里面的內容。我們假設這個線程為B。
public final void acquire(int arg) {if (!tryAcquire(arg) &&acquireQueued(addWaiter(Node.EXCLUSIVE), arg))selfInterrupt();}
這個方法是被定義在AbstractQueuedSynchronized中,里面只有三行代碼,但是需要注意,在這里的時候就可能會發生同步執行。
首先看最下面的如果條件成立執行的方法:selfInterrupt()
static void selfInterrupt() {Thread.currentThread().interrupt();}
這個方法很簡單,令當前線程中斷。但需要注意的是,這個中斷只是把線程里面的中斷標志位改為true,并沒有實際的對線程進行阻塞。線程阻塞已經在上面的兩個判斷條件里面完成了。
然后我們再來看下上面的判斷條件:
首先是tryAcquire(arg),調用非公平鎖的tryAcquire(int),里面又調用了Sync的nonfairTryAcquire(int)方法,通過判斷當前的鎖狀態是否等于0,等于則表示沒有線程獲取鎖(實際有可能是線程B已經執行完成并已經釋放鎖),再次嘗試用CAS操作獲取鎖,獲取成功則返回true,并且記錄當前線程。如果獲取失敗,或者鎖狀態不等于0,則表示已經有線程獲取到鎖,此時會比較記錄的線程是否為當前線程,如果是,則表示是當前線程重入(這里可以看出ReentrantLock是可重入鎖),再令鎖狀態state加1,返回true,否則沒有獲取到鎖返回false。
在這里我們可以看到tryAcquire()目的是再次判斷當前鎖是否是可獲取狀態(線程B已經執行完成并釋放鎖)以及是否是同一個線程的重入操作。獲取鎖成功或者是線程重入則返回true,lock方法就此結束。否則繼續執行第二個條件判斷。
static final class NonfairSync extends Sync {protected final boolean tryAcquire(int acquires) {return nonfairTryAcquire(acquires);}}abstract static class Sync extends AbstractQueuedSynchronizer {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) // overflowthrow new Error("Maximum lock count exceeded");setState(nextc);return true;}return false;}}
再次獲取鎖失敗后,會通過addWaiter()將當前線程添加到FIFO隊列中。
在AQS(隊列同步器)中通過Node內部類來制定一個雙向鏈表,此鏈表采取的是先進先出(FIFO)策略。同時定義了一個頭結點head和尾節點tail,都使用關鍵字volatile來保證多線程的可見性。
private Node addWaiter(Node mode) {Node node = new Node(Thread.currentThread(), mode); //創建新的節點// Try the fast path of enq; backup to full enq on failureNode pred = tail;if (pred != null) { //判斷當前尾節點是否等于nullnode.prev = pred;if (compareAndSetTail(pred, node)) { //尾節點不等于null,通過CAS操作將當前節點替換為鏈表尾節點。替換成功令當前節點作為前一個節點的next節點。替換失敗則說明有其他線程正在操作,進入enq進行操作。pred.next = node; return node; //操作成功,返回當前節點。}}enq(node); //自旋獲取鎖return node;}private final boolean compareAndSetTail(Node expect, Node update) {return unsafe.compareAndSwapObject(this, tailOffset, expect, update); //這里是通過偏移量上值比較來進行值替換。}
//進入這個方法有兩種可能,一是當前鏈表沒有初始化,等于null,二是當前線程與其他線程競爭添加線程到尾節點失敗。private Node enq(final Node node) {for (;;) {Node t = tail;if (t == null) { // Must initializeif (compareAndSetHead(new Node())) //當前鏈表沒有初始化,先進行初始化。添加一個新節點作為頭節點(代表的是當前正在執行的線程),初始化成功,則令首尾節點都等于該節點。初始化失敗,說明已經有其他線程進行了初始化。進入下一個循環。tail = head;} else {node.prev = t;if (compareAndSetTail(t, node)) { //當前鏈表中已經初始化過,將新節點添加在鏈表末尾,添加成功則返回新節點,添加失敗說明有其他線程在競爭添加,進入下一個循環,直到操作成功,當前線程被添加進隊列中。t.next = node;return t;}}}}
新的線程被添加到隊列里面后,再調用方法acquireQueue(Node,int);
這里可以簡單的理解,線程自旋,如果當前線程的前一個節點是頭節點(頭結點代表獲取到鎖且正在執行的線程),說明下一個移出隊列參與競爭鎖的線程是當前線程,再次嘗試獲取鎖,獲取到了說明前一個節點已經執行完,令當前節點替換頭節點,并返回中斷標志位false。
獲取鎖失敗說明上一個線程仍未執行完,或者鎖被其他線程競爭到(新建的線程尚未添加到隊列中,可以參與鎖競爭),同時如果當前線程的上一個節點不是頭節點(說明下一個移出隊列競爭鎖的線程不是當前線程),都會將線程節點的前一個節點的標志位設置為SIGNAL(表示下一個節點需要被unparking),然后令當前線程中斷,暫停循環,等待喚醒。
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 GCfailed = false;return interrupted; //獲取鎖成功返回false;}if (shouldParkAfterFailedAcquire(p, node) &&parkAndCheckInterrupt()) //不會一直循環下去,因為會不斷地消耗資源,適時會進入中斷,等待被喚醒后才繼續自旋。interrupted = true;}} finally {if (failed)cancelAcquire(node);}}final Node predecessor() throws NullPointerException { //獲取當前節點的前節點Node p = prev;if (p == null)throw new NullPointerException();elsereturn p;}private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {int ws = pred.waitStatus; //在這里Node的線程狀態一共有5種情況:SIGNAL=-1,CANCELLED=1,CONDITION=-2,PROPAGATE=-3,以及默認值0if (ws == Node.SIGNAL) //SIGNAL表示喚醒狀態/** This node has already set status asking a release* to signal it, so it can safely park.*/return true;if (ws > 0) { //大于0的只有CANCELLED情況,當前線程被取消執行,因此從隊列中剔除/** Predecessor was cancelled. Skip over predecessors and* indicate retry.*/do {node.prev = pred = pred.prev;} while (pred.waitStatus > 0);pred.next = node;} else { //剩下的不論什么情況,都會利用CAS操作嘗試將節點的waitStatus改為SINGAL,不論操作成功還是失敗,都會返回false/** waitStatus must be 0 or PROPAGATE. Indicate that we* need a signal, but don't park yet. Caller will need to* retry to make sure it cannot acquire before parking.*/compareAndSetWaitStatus(pred, ws, Node.SIGNAL);}return false;}private static final boolean compareAndSetWaitStatus(Node node,int expect,int update) { //利用CAS操作修改節點的waitStatus值return unsafe.compareAndSwapInt(node, waitStatusOffset,expect, update);}private final boolean parkAndCheckInterrupt() {LockSupport.park(this);return Thread.interrupted();}private void cancelAcquire(Node node) {// Ignore if node doesn't existif (node == null)return;node.thread = null;// Skip cancelled predecessorsNode pred = node.prev;while (pred.waitStatus > 0)node.prev = pred = pred.prev;// predNext is the apparent node to unsplice. CASes below will// fail if not, in which case, we lost race vs another cancel// or signal, so no further action is necessary.Node predNext = pred.next;// Can use unconditional write instead of CAS here.// After this atomic step, other Nodes can skip past us.// Before, we are free of interference from other threads.node.waitStatus = Node.CANCELLED;// If we are the tail, remove ourselves.if (node == tail && compareAndSetTail(node, pred)) {compareAndSetNext(pred, predNext, null);} else {// If successor needs signal, try to set pred's next-link// so it will get one. Otherwise wake it up to propagate.int ws;if (pred != head &&((ws = pred.waitStatus) == Node.SIGNAL ||(ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&pred.thread != null) {Node next = node.next;if (next != null && next.waitStatus <= 0)compareAndSetNext(pred, predNext, next);} else {unparkSuccessor(node);}node.next = node; // help GC }}
由此,整個非公平鎖的加鎖過程結束,總結一下:
1.如果state位是0,則表示沒有線程獲取對象鎖,通過CAS操作設置state位從0到1,嘗試獲取鎖
2.獲取鎖成功,記錄當前獲取鎖的線程。流程結束。
3.獲取失敗,判斷是否是已經獲取了鎖的線程再次獲取(通過第二步里面記錄的線程與當前線程判斷是否相等),如果是,令state再加1,流程結束。
4.如果不是,將線程添加到FIFO鏈表隊列中,然后進行自旋。
5.自旋時會判斷當前線程是否是head節點的next,如果是則再次嘗試獲取鎖,獲取到了后將頭節點替換為當前節點,返回false。流程結束。
6.自旋一定次數后仍未獲取到鎖,或當前線程節點不是下一個參與競爭鎖的線程,則進入中斷。等待被喚醒后繼續自旋。
?
公平鎖的Lock()方法:
final void lock() {acquire(1);}
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;}}
公平鎖與非公平鎖的加鎖方法區別在于,tryAcquire(int)方法的不同。公平鎖中要判斷隊列里第一個線程是否是當前線程,如果是,則允許它獲取鎖,如果不是,則不能獲取。
?
下面看一下解鎖方法:unlock()
public void unlock() {sync.release(1);}
內部不分公平鎖與非公平鎖,一律調用AbstractQueuedSynchronized方法的release(int)。
public final boolean release(int arg) {if (tryRelease(arg)) {Node h = head;if (h != null && h.waitStatus != 0)unparkSuccessor(h);return true;}return false;}
先看第一行的判斷:if(tryRelease(arg))
里面先判斷了鎖指向的線程與當前線程相等,不相等則拋出異常。
再令status減1,判斷結果是否等于0。等于0說明可以釋放鎖,將鎖指向的線程改為null,status改為0,返回true。
不等于0則說明仍未全部執行完重入的操作,令status自減一,返回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;}
判斷為false則釋放鎖失敗,判斷為true則繼續執行if里面內容。
if里面主要是判斷了鏈表隊列head里面有等待喚醒的其他線程節點,對他們進行一個喚醒。
private void unparkSuccessor(Node node) {/** If status is negative (i.e., possibly needing signal) try* to clear in anticipation of signalling. It is OK if this* fails or if status is changed by waiting thread.*/int ws = node.waitStatus;if (ws < 0)compareAndSetWaitStatus(node, ws, 0); //將waitStatus賦值為初始狀態0/** Thread to unpark is held in successor, which is normally* just the next node. But if cancelled or apparently null,* traverse backwards from tail to find the actual* non-cancelled successor.*/Node s = node.next;if (s == null || s.waitStatus > 0) { //下一個節點等于null或者被取消執行,從尾節點開始向前遍歷,找到最頭位置上的節點s = null;for (Node t = tail; t != null && t != node; t = t.prev)if (t.waitStatus <= 0)s = t;}if (s != null) //喚醒隊列中的下一個可執行的節點。LockSupport.unpark(s.thread);}
解鎖流程總結:
1.鎖指向的線程與當前線程必須是同一個線程。
2.鎖標志位status必須已經減到0。
3.判斷鏈表隊列不等于null,并且頭節點的waitStatus標志位不等于0,需要喚醒下一個節點。否則返回true,業務結束。
4.喚醒下一個節點首先利用CAS操作將waitStatus的標志位改為0,然后再按隊列順序獲取下一個節點。
5.如果獲取的新節點等于null,或者waitStatus位等于1(表示已經被取消執行),則從尾節點向前遍歷,直到遇見最前面的非null非當前線程節點的節點。
6.喚醒獲取的新節點。業務結束。
?