擼一擼ReentrantLock的源碼

<b>synchronized:</b>把代碼塊聲明為 synchronized,有兩個(gè)重要后果瞪浸,通常是指該代碼具有 原子性(atomicity)可見(jiàn)性(visibility)漓糙。原子性意味著一個(gè)線程一次只能執(zhí)行由一個(gè)指定監(jiān)控對(duì)象(lock)保護(hù)的代碼潦匈,從而防止多個(gè)線程在更新共享狀態(tài)時(shí)相互沖突闹丐『崤梗可見(jiàn)性表示每次都從內(nèi)存中拿去最新的值,以及代碼塊結(jié)束之前將最新的值更新到內(nèi)存
<b>ReentrantLock:</b>相對(duì)于synchronized添加了類(lèi)似鎖投票卿拴、定時(shí)鎖等候和可中斷鎖等候的一些特性衫仑。此外,它還提供了在激烈爭(zhēng)用情況下更佳的性能堕花。(換句話說(shuō)文狱,當(dāng)許多線程都想訪問(wèn)共享資源時(shí),JVM 可以花更少的時(shí)候來(lái)調(diào)度線程缘挽,把更多時(shí)間用在執(zhí)行線程上如贷。)
之前也就是拿ReentrantLock來(lái)用用或者主要還是用synchronized比較多陷虎,還是想擼擼ReentrantLock的源代碼:
<b>uml 類(lèi)圖梳理:</b>
<pre>


</pre>
<b>Sync類(lèi):</b>
<pre>
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(); //抽象方法被公平鎖和非公平鎖分別實(shí)現(xiàn)
/
*
* 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(); //獲取基類(lèi)AbstractQueuedSynchronizer的 volatile state屬性
if (c == 0) { //表示空閑狀態(tài)
if (compareAndSetState(0, acquires)) { // 使用了sun.misc下面的UnSafe類(lèi)的compareAndSwapInt方法到踏,跟AtomicInteger等原子性類(lèi)實(shí)現(xiàn)一樣
setExclusiveOwnerThread(current); //設(shè)置鎖被占用的線程為當(dāng)前線程
return true;
}
}
else if (current == getExclusiveOwnerThread()) { //如果鎖已經(jīng)被當(dāng)前線程使用杠袱,重用鎖
int nextc = c + acquires; //在原有的鎖上面使state的值變大,所以如果釋放鎖的話需要使state直到變成0窝稿,單純減1沒(méi)有釋放鎖
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; //使得state值變小
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() {  //其實(shí)上面的判斷可用改成直接調(diào)用isHeldExclusively
        // While we must in general read state before owner,
        // we don't need to do so to check if current thread is owner
        return 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() {  //獲取鎖被入次數(shù),因?yàn)榫€程可以重入鎖
        return isHeldExclusively() ? getState() : 0;
    }

    final boolean isLocked() {  //判斷鎖是否被占用
        return getState() != 0;
    }

    /**
     * Reconstitutes this lock instance from a stream.
     * @param s the stream
     */
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        s.defaultReadObject();
        setState(0); // reset to unlocked state
    }
}

</pre>
<b>UnSafe.compareAndSwapInt補(bǔ)充:</b>CAS是項(xiàng)樂(lè)觀鎖技術(shù)楣富,當(dāng)多個(gè)線程嘗試使用CAS同時(shí)更新同一個(gè)變量時(shí),只有其中一個(gè)線程能更新變量的值伴榔,而其它線程都失敗纹蝴,失敗的線程并不會(huì)被掛起,而是被告知這次競(jìng)爭(zhēng)中失敗踪少,并可以再次嘗試塘安。CAS有3個(gè)操作數(shù),內(nèi)存值V援奢,舊的預(yù)期值A(chǔ)兼犯,要修改的新值B。當(dāng)且僅當(dāng)預(yù)期值A(chǔ)和內(nèi)存值V相同時(shí)集漾,將內(nèi)存值V修改為B切黔,否則什么都不做。

<b>NonfairSync類(lèi):</b>
<pre>
/**
* 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))  //這是跟公平鎖的主要區(qū)別具篇,一上來(lái)就試探鎖是否空閑纬霞,可以插隊(duì)
            setExclusiveOwnerThread(Thread.currentThread());
        else
            acquire(1); //具體實(shí)現(xiàn)看如下
    }

    protected final boolean tryAcquire(int acquires) {
        return nonfairTryAcquire(acquires);
    }
}

AbstractQueuedSynchronizer類(lèi)的acquire實(shí)現(xiàn):
public final void acquire(int arg) {
if (!tryAcquire(arg) && //嘗試獲取鎖
acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //如果獲取鎖失敗則丟到鎖等待的隊(duì)列中
selfInterrupt();
}
/**
* Creates and enqueues node for current thread and given mode.
*
* @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
* @return the new node
/
private Node addWaiter(Node mode) {
Node node = new Node(Thread.currentThread(), mode);
// Try the fast path of enq; backup to full enq on failure
Node pred = tail;
if (pred != null) {
node.prev = pred;
if (compareAndSetTail(pred, node)) {
pred.next = node;
return node;
}
}
enq(node); //其實(shí)這個(gè)主要是處理當(dāng)pred == null 時(shí)處理兩步 1、新建head 且 tail = head 2驱显、tail = node 里面是個(gè)循環(huán)操作诗芜,不為空時(shí)只處理第二步,我看了一下enq這個(gè)方法有好幾處在用所以作者把它包裝起來(lái)
return node;
}
<b>雙向鏈表圖:</b>

鏈表.png

<b>acquireQueued源碼:</b>
/
*
* Acquires in exclusive uninterruptible mode for thread already in
* queue. Used by condition wait methods as well as acquire.
*
* @param node the node
* @param arg the acquire argument
* @return {@code true} if interrupted while waiting
/
final boolean acquireQueued(final Node node, int arg) {
boolean failed = true;
try {
boolean interrupted = false;
for (;;) { //循環(huán):如果獲取到鎖則結(jié)束埃疫,如果前面還有節(jié)點(diǎn)則等待前面節(jié)點(diǎn)獲取鎖結(jié)束以后釋放信號(hào)
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) && 判斷后續(xù)線程是否應(yīng)該被阻塞伏恐,這里的p的后續(xù)線程其實(shí)就是當(dāng)前線程
parkAndCheckInterrupt()) //里面 LockSupport.park(this);阻塞當(dāng)前線程,以及檢測(cè)是否被中斷
interrupted = true;
}
} finally {
if (failed)
cancelAcquire(node);
}
}
//shouldParkAfterFailedAcquire
private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
int ws = pred.waitStatus;
if (ws == Node.SIGNAL) //CANCELLED[1]:當(dāng)前線程已被取消
SIGNAL[-1]:后繼節(jié)點(diǎn)將被或者已經(jīng)被阻塞,所以當(dāng)前節(jié)點(diǎn)在釋放或者取消時(shí),需要unpark它的后繼節(jié)點(diǎn)帮孔。
CONDITION[-2]:當(dāng)前線程(處在Condition休眠狀態(tài))在等待Condition喚醒
PROPAGATE[-3]:(共享鎖)其它線程獲取到“共享鎖”
/

* This node has already set status asking a release
* to signal it, so it can safely park.
/
return true;
if (ws > 0) {
/

* Predecessor was cancelled. Skip over predecessors and
* indicate retry.
/
do {
node.prev = pred = pred.prev;
} while (pred.waitStatus > 0);
pred.next = node;
} else {
/

* 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;
}
</pre>
<b>FairSync類(lèi)源碼:</b>
<pre>
/
*
* Sync object for fair locks
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -3000897897090466540L;

    final void lock() {  //相對(duì)于NonfairSync的lock少了一來(lái)就compareAndSetState(0, 1)空閑就上鎖
        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() &&   //相對(duì)于NonfairSync的tryAcquire就是多了一個(gè)先判斷等待隊(duì)列中是否有其它等待的線程
                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;
    }
}

</pre>

<b>NonfairSync 和 FairSync比較分析:</b>非公平鎖來(lái)了先判斷是否空閑烫堤,空閑就占用鎖,公平鎖先查看等待隊(duì)列中是否有其它線程等待恒傻,按序獲取鎖不能插隊(duì)。可想而知非公平鎖效率更高闻鉴,但是公平鎖也有其特定的使用場(chǎng)景。new ReentrantLock() 默認(rèn)是指定的非公平鎖也相當(dāng)于new ReentrantLock(false) 表示調(diào)用NonfairSync 的非公平鎖,new ReentrantLock(true) 表示調(diào)用 FairSync的公平鎖

<b>ReentrantLock如何響應(yīng)鎖中斷茂洒?</b>
先說(shuō)說(shuō)線程的打擾機(jī)制孟岛,每個(gè)線程都有一個(gè) 打擾 標(biāo)志。
這里分兩種情況:

  1. 線程在sleep或wait,join, 此時(shí)如果別的線程調(diào)用此線程的 interrupt()方法渠羞,此線程會(huì)被喚醒并被要求處理InterruptedException

  2. 此線程在運(yùn)行中斤贰, 則不會(huì)收到提醒。但是 此線程的 “打擾標(biāo)志”會(huì)被設(shè)置次询, 可以通過(guò)isInterrupted()查看并 作出處理
    lockInterruptibly()和上面的第一種情況是一樣的荧恍, 線程在請(qǐng)求lock并被阻塞時(shí),如果被interrupt屯吊,則此線程會(huì)被喚醒并拋出InterruptedException
    上個(gè)例子:
    <pre>
    public class Test {
    public static void test() throws Exception {
    final Lock lock = new ReentrantLock();
    Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    Thread.sleep(2000);
    lock.lockInterruptibly();
    } catch (InterruptedException e) {
    System.out.println(Thread.currentThread().getName() + " interrupted.");
    }
    }
    });
    t1.start();
    t1.interrupt();
    Thread.sleep(10000000);
    }

    public static void main(String[] args) throws Exception {
    Test.test();
    }
    }
    輸出結(jié)果為:
    Thread-0 interrupted.
    </pre>
    <pre>
    public void lockInterruptibly() throws InterruptedException {
    sync.acquireInterruptibly(1);
    }
    基類(lèi)代碼:
    public final void acquireInterruptibly(int arg)
    throws InterruptedException {
    if (Thread.interrupted())
    throw new InterruptedException();
    if (!tryAcquire(arg))
    doAcquireInterruptibly(arg);
    }
    doAcquireInterruptibly的實(shí)現(xiàn)跟acquireQueued實(shí)現(xiàn)有些類(lèi)似送巡。
    doAcquireInterruptibly以 throw new InterruptedException()來(lái)中斷
    acquireQueued 即使檢測(cè)到了Thread.interruptted為true一樣會(huì)繼續(xù)嘗試獲取鎖,失敗則繼續(xù)等待只是在最后獲取鎖成功之后在把當(dāng)前線程置為 interrupted = true狀態(tài)盒卸。
    </pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末骗爆,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子蔽介,更是在濱河造成了極大的恐慌摘投,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件屉佳,死亡現(xiàn)場(chǎng)離奇詭異谷朝,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)武花,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)圆凰,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人体箕,你說(shuō)我怎么就攤上這事专钉。” “怎么了累铅?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵跃须,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我娃兽,道長(zhǎng)菇民,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任投储,我火速辦了婚禮第练,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘玛荞。我一直安慰自己娇掏,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布勋眯。 她就那樣靜靜地躺著婴梧,像睡著了一般下梢。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上塞蹭,一...
    開(kāi)封第一講書(shū)人閱讀 51,598評(píng)論 1 305
  • 那天孽江,我揣著相機(jī)與錄音,去河邊找鬼浮还。 笑死竟坛,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的钧舌。 我是一名探鬼主播,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼涎跨,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼洼冻!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起隅很,我...
    開(kāi)封第一講書(shū)人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤撞牢,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后叔营,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體屋彪,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年绒尊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了畜挥。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡婴谱,死狀恐怖蟹但,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情谭羔,我是刑警寧澤华糖,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站瘟裸,受9級(jí)特大地震影響客叉,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜话告,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一兼搏、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧超棺,春花似錦向族、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)再扭。三九已至,卻和暖如春夜矗,著一層夾襖步出監(jiān)牢的瞬間泛范,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工紊撕, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留罢荡,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓对扶,卻偏偏與公主長(zhǎng)得像区赵,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子浪南,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容