AQS

paper傳送門

/**

* Provides a framework for implementing blocking locks and related

* synchronizers (semaphores, events, etc) that rely on

* first-in-first-out (FIFO) wait queues.  This class is designed to

* be a useful basis for most kinds of synchronizers that rely on a

* single atomic int value to represent state. Subclasses

* must define the protected methods that change this state, and which

* define what that state means in terms of this object being acquired

* or released.  Given these, the other methods in this class carry

* out all queuing and blocking mechanics. Subclasses can maintain

* other state fields, but only the atomically updated int

* value manipulated using methods {@link #getState}, {@link

* #setState} and {@link #compareAndSetState} is tracked with respect

* to synchronization.

*/

*      +------+  prev +-----+       +-----+

* head |      | <---- |     | <---- |     |  tail

*      +------+       +-----+       +-----+

在AQS中維護(hù)著一個(gè)FIFO的同步隊(duì)列,當(dāng)線程獲取同步狀態(tài)失敗后鞭执,則會(huì)加入到這個(gè)CLH同步隊(duì)列的對(duì)尾并一直保持著自旋。在CLH同步隊(duì)列中的線程在自旋時(shí)會(huì)判斷其前驅(qū)節(jié)點(diǎn)是否為首節(jié)點(diǎn)包竹,如果為首節(jié)點(diǎn)則不斷嘗試獲取同步狀態(tài)厉碟,獲取成功則退出CLH同步隊(duì)列。當(dāng)線程執(zhí)行完邏輯后鼎姊,會(huì)釋放同步狀態(tài)骡和,釋放后會(huì)喚醒其后繼節(jié)點(diǎn)。

它維護(hù)了一個(gè)volatile int state(代表共享資源)和一個(gè)FIFO線程等待隊(duì)列(多線程爭(zhēng)用資源被阻塞時(shí)會(huì)進(jìn)入此隊(duì)列)相寇。這里volatile是核心關(guān)鍵詞慰于,具體volatile的語(yǔ)義,在此不述唤衫。state的訪問(wèn)方式有三種:

getState()

setState()

compareAndSetState()

AQS定義兩種資源共享方式:

  • Exclusive(獨(dú)占婆赠,只有一個(gè)線程能執(zhí)行,如ReentrantLock)
  • Share(共享佳励,多個(gè)線程可同時(shí)執(zhí)行休里,如Semaphore/CountDownLatch)

ReentrantLock的公平和非公平如何實(shí)現(xiàn)的呢?它內(nèi)部有幾個(gè)類

abstract static class Sync extends AbstractQueuedSynchronizer

static final class NonfairSync extends Sync

static final class FairSync extends Sync

對(duì)于State都是tryAcquire方法

公平鎖

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;
        }
    }
}

非公平鎖

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);
        }
    }
/**
         * 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;
        }

可以發(fā)現(xiàn)區(qū)別在于公平鎖多了一層hasQueuedPredecessors()判斷

/**
     * Queries whether any threads have been waiting to acquire longer
     * than the current thread.
     *
     * <p>An invocation of this method is equivalent to (but may be
     * more efficient than):
     *  <pre> {@code
     * getFirstQueuedThread() != Thread.currentThread() &&
     * hasQueuedThreads()}</pre>
     *
     * <p>Note that because cancellations due to interrupts and
     * timeouts may occur at any time, a {@code true} return does not
     * guarantee that some other thread will acquire before the current
     * thread.  Likewise, it is possible for another thread to win a
     * race to enqueue after this method has returned {@code false},
     * due to the queue being empty.
     *
     * <p>This method is designed to be used by a fair synchronizer to
     * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
     * Such a synchronizer's {@link #tryAcquire} method should return
     * {@code false}, and its {@link #tryAcquireShared} method should
     * return a negative value, if this method returns {@code true}
     * (unless this is a reentrant acquire).  For example, the {@code
     * tryAcquire} method for a fair, reentrant, exclusive mode
     * synchronizer might look like this:
     *
     *  <pre> {@code
     * protected boolean tryAcquire(int arg) {
     *   if (isHeldExclusively()) {
     *     // A reentrant acquire; increment hold count
     *     return true;
     *   } else if (hasQueuedPredecessors()) {
     *     return false;
     *   } else {
     *     // try to acquire normally
     *   }
     * }}</pre>
     *
     * @return {@code true} if there is a queued thread preceding the
     *         current thread, and {@code false} if the current thread
     *         is at the head of the queue or the queue is empty
     * @since 1.7
     */
    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());
    }

doc 和 代碼都很清楚, 此方法判斷當(dāng)前線程之前是否還有其他線程在(非頭結(jié)點(diǎn))

最后編輯于
?著作權(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)店門毡咏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(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)容