Java可重入鎖詳解

作者: 一字馬胡
轉(zhuǎn)載標(biāo)志 【2017-11-03】

更新日志

日期 更新內(nèi)容 備注
2017-11-03 添加轉(zhuǎn)載標(biāo)志 持續(xù)更新

前言

在java中,鎖是實(shí)現(xiàn)并發(fā)的關(guān)鍵組件,多個(gè)線程之間的同步關(guān)系需要鎖來保證,所謂鎖,其語義就是資源獲取到資源釋放的一系列過程,使用lock的意圖就是想要進(jìn)入臨界區(qū)對(duì)共享資源執(zhí)行操作,使用unlock說明線程已經(jīng)完成了相關(guān)工作或者發(fā)生了異常從而離開臨界區(qū)釋放共享資源,可以說,在多線程環(huán)境下,鎖是一個(gè)必不可少的組件。我們最為常用的并發(fā)鎖是synchronized關(guān)鍵字,在最新的jdk中,synchronized的性能已經(jīng)有了極大的提升了,而且未來還會(huì)對(duì)它做更進(jìn)一步的優(yōu)化,最為重要的是synchronized使用起來特別方便,基本不需要要我們考慮太多的內(nèi)容,只需要將臨界區(qū)的代碼放在synchronized關(guān)鍵字里面,然后設(shè)定好需要鎖定的對(duì)象,synchronized就會(huì)自動(dòng)為進(jìn)入的并發(fā)線程lock和unlock。在大多數(shù)情況下,我們寫并發(fā)代碼使用synchronized就足夠了,而且使用synchronized也是首選,不過如果我們希望更加靈活的使用鎖來做并發(fā),那么java還提供了一個(gè)借口Lock,本文并不會(huì)對(duì)synchronized進(jìn)行分析總結(jié),本文的重點(diǎn)在Lock接口,以及實(shí)現(xiàn)了Lock接口的一些子類的分析總結(jié)。

為了本文的完整性,可以參考Java同步框架AbstractQueuedSynchronizer,這個(gè)俗稱為AQS的東西是Lock接口實(shí)現(xiàn)的根本,它實(shí)現(xiàn)了Lock的全部語義,可以說,java的Lock接口的子類就是借助AQS來實(shí)現(xiàn)了lock和unlock的,理解了AQS,就可以很好的理解java中的鎖了。

Lock接口以及ReadWriteLock接口

下面首先展示出了Lock接口的內(nèi)容,然后是ReadWriteLock的接口,本文主要分析這兩個(gè)接口的幾個(gè)子類的實(shí)現(xiàn)細(xì)節(jié)。

Lock接口

public interface ReadWriteLock {
    /**
     * Returns the lock used for reading.
     *
     * @return the lock used for reading
     */
    Lock readLock();

    /**
     * Returns the lock used for writing.
     *
     * @return the lock used for writing
     */
    Lock writeLock();
}

Lock接口提供了lock和unlock方法,提供加鎖和釋放鎖的語義,lockInterruptibly方法可以響應(yīng)中斷,lock方法會(huì)阻塞線程直到獲取到鎖,而tryLock方法則會(huì)立刻返回,返回true代表獲取鎖成功,而返回false則說明獲取不到鎖。newCondition方法返回一個(gè)條件變量,一個(gè)條件變量也可以做線程間通信來同步線程。多個(gè)線程可以等待在同一個(gè)條件變量上,一些線程會(huì)在某些情況下通知等待在條件變量上的線程,而有些變量在某些情況下會(huì)加入到條件變量上的等待隊(duì)列中去。

ReadWriteLock是讀寫鎖,可以對(duì)共享變量的讀寫提供并發(fā)支持,ReadWriteLock接口的兩個(gè)方法分別返回一個(gè)讀鎖和一個(gè)寫鎖。本文將基于上面提到的兩個(gè)接口Lock和ReadWriteLock,對(duì)Lock的子類ReentrantLock和ReadWriteLock的子類ReentrantReadWriteLock進(jìn)行一些分析總結(jié),以備未來不時(shí)之需。

ReentrantLock

Java同步框架AbstractQueuedSynchronizer提到了兩個(gè)概念,一個(gè)是獨(dú)占鎖,一個(gè)是共享鎖,所謂獨(dú)占鎖就是只能有一個(gè)線程獲取到鎖,其他線程必須在這個(gè)鎖釋放了鎖之后才能競(jìng)爭(zhēng)而獲得鎖。而共享鎖則可以允許多個(gè)線程獲取到鎖。具體的分析不再本文的分析范圍之內(nèi)。

ReentrantLock翻譯過來為可重入鎖,它的可重入性表現(xiàn)在同一個(gè)線程可以多次獲得鎖,而不同線程依然不可多次獲得鎖,這在下文中會(huì)進(jìn)行分析。下文會(huì)分析它是如何借助AQS來實(shí)現(xiàn)lock和unlock的,本文只關(guān)注核心方法,比如lock和unlock,而不會(huì)去詳細(xì)的描述所有的方法。ReentrantLock分為公平鎖和非公平鎖,公平鎖保證等待時(shí)間最長(zhǎng)的線程將優(yōu)先獲得鎖,而非公平鎖并不會(huì)保證多個(gè)線程獲得鎖的順序,但是非公平鎖的并發(fā)性能表現(xiàn)更好,ReentrantLock默認(rèn)使用非公平鎖。下面分公平鎖和非公平鎖來分析一下ReentrantLock的代碼。

鎖Sync

在文章Java同步框架AbstractQueuedSynchronizer中已經(jīng)提到了如何通過AQS來實(shí)現(xiàn)鎖的方法,那就是繼承AbstractQueuedSynchronizer類,然后使用它提供的方法來實(shí)現(xiàn)自己的鎖。ReentrantLock的Sync也是通過這個(gè)方法來實(shí)現(xiàn)鎖的。

Sync有一個(gè)抽象方法lock,其子類FairSync和NonfairSync分別實(shí)現(xiàn)了公平上鎖和非公平上鎖。nonfairTryAcquire方法用于提供可重入的非公平上鎖,之所以把它放在Sync中而不是在子類NonfairSync中(FairSync中有公平的可重入上鎖版本的實(shí)現(xiàn)),是因?yàn)閚onfairTryAcquire不僅在NonfairSync中被使用了,而且在ReentrantLock.tryLock里面也使用到了。對(duì)于它的分析留到NonfairSync里面再分析。

Sync中還需要注意的一個(gè)方法是tryRelease,執(zhí)行這個(gè)方法說明線程在離開臨界區(qū),下面是tryRelease方法的代碼:


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

tryRelease方法重寫了父類的tryRelease方法,而父類的tryRelease方法在release方法中被調(diào)用,而release方法最后會(huì)被用于實(shí)現(xiàn)ReentrantLock的unlock方法。所以理解了該方法,就理解了ReentrantLock的unlock邏輯。

從上面展示的代碼分析,getState方法獲取當(dāng)前的共享變量,getState方法的返回值代表了有多少線程獲取了該條件變量,而release代表著想要釋放的次數(shù),然后根據(jù)這兩個(gè)值計(jì)算出最新的state值,接著判斷當(dāng)前線程是否獨(dú)占了鎖,如果不是,那么就拋出異常,否則繼續(xù)接下來的流程。如果最新的state為0了,說明鎖已經(jīng)被釋放了,可以被其他線程獲取了。然后更新state值。

公平鎖FairSync

FairSync實(shí)現(xiàn)了公平鎖的lock和tryAcquire方法,下面分別看一下這兩個(gè)方法的實(shí)現(xiàn)細(xì)節(jié):


        final void lock() {
            acquire(1);
        }

可以看到,F(xiàn)airSync的lock實(shí)現(xiàn)使用了AQS提供的acquire方法,這個(gè)方法的詳細(xì)解析見Java同步框架AbstractQueuedSynchronizer

下面是tryAcquire方法的細(xì)節(jié):


        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實(shí)現(xiàn)和非公平鎖的tryAcquire實(shí)現(xiàn)的區(qū)別在于:公平鎖多加了一個(gè)判斷條件:hasQueuedPredecessors,如果發(fā)現(xiàn)有線程在等待獲取鎖了,那么就直接返回false,否則在繼承嘗試獲取鎖,這樣就保證了線程是按照排隊(duì)時(shí)間來有限獲取鎖的。而非公平鎖的實(shí)現(xiàn)則不考慮是否有節(jié)點(diǎn)在排隊(duì),會(huì)直接去競(jìng)爭(zhēng)鎖,如果獲取成功就返回true,否則返回false。

當(dāng)然,這些分支執(zhí)行的條件是state為0,也就是說當(dāng)前沒有線程獨(dú)占著鎖,或者獲取鎖的線程就是當(dāng)前獨(dú)占著鎖的線程,如果是前者,就按照上面分析的流程進(jìn)行獲取鎖,如果是后者,則更新state的值,如果不是上述的兩種情況,那么直接返回false說明嘗試獲取鎖失敗。

非公平鎖NonfairSync

公平鎖的lock使用了AQS的acquire,而acquire會(huì)將參與鎖競(jìng)爭(zhēng)的線程加入到等待隊(duì)列中去按順序獲得鎖,隊(duì)列頭部的節(jié)點(diǎn)代表著當(dāng)前獲得鎖的節(jié)點(diǎn),頭結(jié)點(diǎn)釋放鎖之后會(huì)喚醒其后繼節(jié)點(diǎn),然后讓后繼節(jié)點(diǎn)來競(jìng)爭(zhēng)獲取鎖,這樣就可以保證鎖的獲取是按照一定的優(yōu)先級(jí)來的。而非公平鎖的實(shí)現(xiàn)則會(huì)首先嘗試去競(jìng)爭(zhēng)鎖,如果不成功,再走AQS提供的acquire方法,下面是NonfairSync的lock方法:


       final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }

非公平鎖的tryAcquire方法使用了父類的nonfairTryAcquire方法來實(shí)現(xiàn)。

ReentrantLock上鎖和釋放鎖

說完了Sync類和其兩個(gè)子類,現(xiàn)在來看一下ReentrantLock是如何使用這兩個(gè)類來實(shí)現(xiàn)lock和unlock的。首先是ReentrantLock的構(gòu)造方法:


    /**
     * Creates an instance of {@code ReentrantLock}.
     * This is equivalent to using {@code ReentrantLock(false)}.
     */
    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();
    }

默認(rèn)構(gòu)造函數(shù)使用了非公平鎖來提高并發(fā)度,一般情況下使用默認(rèn)構(gòu)造函數(shù)即可。而在一些特殊的情景下,需要使用公平鎖的話就傳遞一個(gè)true的參數(shù)。下面是lock和unlock方法的細(xì)節(jié),lock使用了Sync的lock方法,而unlock使用了AQS的release方法,而release方法使用了其tryRelease方法,而這個(gè)方法在Sync類中被重寫,上面我們已經(jīng)有過分析。


    public void lock() {
        sync.lock();
    }
    
    public void unlock() {
        sync.release(1);
    }    

newCondition方法

newCondition這個(gè)方法需要一些篇幅來描述一下,而newCondition方法的返回內(nèi)容涉及AQS類中的內(nèi)部類ConditionObject,所以也就是分析一下ConditionObject這個(gè)類的一些細(xì)節(jié)。下面的圖片展示了ConditionObject這個(gè)類的類圖,可以看出,它實(shí)現(xiàn)了Condition的所有方法。

ConditionObject類圖

關(guān)于Condition接口的描述,可以參考下面的文檔內(nèi)容:


 * Conditions (also known as condition queues or
 * condition variables) provide a means for one thread to
 * suspend execution (to wait) until notified by another
 * thread that some state condition may now be true.  Because access
 * to this shared state information occurs in different threads, it
 * must be protected, so a lock of some form is associated with the
 * condition. The key property that waiting for a condition provides
 * is that it atomically releases the associated lock and
 * suspends the current thread, just like {@code Object.wait}.

await和await(long time, TimeUnit unit)方法

接下來分析一下ConditionObject類是如何實(shí)現(xiàn)Condition接口的方法的。首先是await方法,這個(gè)方法的意思是讓當(dāng)前線程等待直到有別的線程signalled,或者被interrupted。調(diào)用此方法的線程會(huì)被阻塞直到有其他的線程喚醒或者打斷它。下面是它的實(shí)現(xiàn)。


        public final void await() throws InterruptedException {
            if (Thread.interrupted())
                throw new InterruptedException();
            Node node = addConditionWaiter();
            int savedState = fullyRelease(node);
            int interruptMode = 0;
            while (!isOnSyncQueue(node)) {
                LockSupport.park(this);
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
                    break;
            }
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
                interruptMode = REINTERRUPT;
            if (node.nextWaiter != null) // clean up if cancelled
                unlinkCancelledWaiters();
            if (interruptMode != 0)
                reportInterruptAfterWait(interruptMode);
        }

     

首先,如果線程被中斷了,那么拋出異常。否則調(diào)用addConditionWaiter方法生成一個(gè)Node,下面來看一下addConditionWaiter這個(gè)方法的細(xì)節(jié):


        private Node addConditionWaiter() {
            Node t = lastWaiter;
            // If lastWaiter is cancelled, clean out.
            if (t != null && t.waitStatus != Node.CONDITION) {
                unlinkCancelledWaiters();
                t = lastWaiter;
            }
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
            if (t == null)
                firstWaiter = node;
            else
                t.nextWaiter = node;
            lastWaiter = node;
            return node;
        }

lastWaiter是等待在該Condition上的隊(duì)列末尾的線程,根據(jù)代碼,首先,如果最后一個(gè)線程從Condition上被取消了,并且當(dāng)前線程并沒有在該Condition的等待隊(duì)列上,那么就將當(dāng)前線程作為該Condition上等待隊(duì)列的末尾節(jié)點(diǎn)。如果上面的條件不成立,那么就使用當(dāng)前線程生成一個(gè)新的Node,然后將其狀態(tài)變?yōu)镹ode.CONDITION代表其等待在某個(gè)Condition上,然后將該新的節(jié)點(diǎn)添加到隊(duì)列的末尾。

現(xiàn)在回頭看await方法,我們發(fā)現(xiàn)addConditionWaiter的作用就是將當(dāng)前線程添加到Condition的等待隊(duì)列上去。接下來的步驟特別關(guān)鍵。await方法調(diào)用了fullyRelease方法,我們來看一下這個(gè)方法是干嘛用的:


    final int fullyRelease(Node node) {
        boolean failed = true;
        try {
            int savedState = getState();
            if (release(savedState)) {
                failed = false;
                return savedState;
            } else {
                throw new IllegalMonitorStateException();
            }
        } finally {
            if (failed)
                node.waitStatus = Node.CANCELLED;
        }
    }

fullyRelease會(huì)調(diào)用release方法來是釋放當(dāng)前線程的同步狀態(tài),并且返回釋放之后的狀態(tài)值,這個(gè)值在await方法中作為了acquireQueued方法參數(shù),這個(gè)方法在稍后分析。現(xiàn)在來看一下接下來的步驟,在獲得了當(dāng)前線程的state值了之后,就會(huì)進(jìn)入一個(gè)while循環(huán)中去,while循環(huán)停止的條件是isOnSyncQueue(node)這個(gè)方法返回true,這個(gè)方法是用來判斷一個(gè)Node是否在AQS的等待隊(duì)列中的,下面是其方法內(nèi)容:


    final boolean isOnSyncQueue(Node node) {
        if (node.waitStatus == Node.CONDITION || node.prev == null)
            return false;
        if (node.next != null) // If has successor, it must be on queue
            return true;
 
        return findNodeFromTail(node);
    }

    private boolean findNodeFromTail(Node node) {
        Node t = tail;
        for (;;) {
            if (t == node)
                return true;
            if (t == null)
                return false;
            t = t.prev;
        }
    }

也就是說,只要當(dāng)前線程的Node還在Condition上等待的話,就會(huì)一直在while循環(huán)中等待,而這個(gè)等待被破除的關(guān)鍵是signal方法,后面會(huì)分析到。我們現(xiàn)在假設(shè)signal方法運(yùn)行完了,并且當(dāng)前線程已經(jīng)被添加到了AQS的SYNC等待隊(duì)列中去了,那么接下來就使用我們一開始獲取到的state值來競(jìng)爭(zhēng)鎖了,而這個(gè)競(jìng)爭(zhēng)就是AQS的邏輯,下面的方法就是這個(gè)競(jìng)爭(zhēng)去獲取鎖的方法:


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

這個(gè)方法會(huì)自旋的來獲得同步變量,這個(gè)方法中的循環(huán)結(jié)束的條件是:

  1. 該節(jié)點(diǎn)的前驅(qū)節(jié)點(diǎn)是頭結(jié)點(diǎn),頭結(jié)點(diǎn)代表的是獲得鎖的節(jié)點(diǎn),只有它釋放了state其他線程才能獲得這個(gè)變量的所有權(quán)
  2. 在條件1的前提下,方法tryAcquire返回true,也就是可以獲得同步資源state

整個(gè)await方法總結(jié)起來就是首先釋放當(dāng)前線程的條件變量,然后獲取到釋放完了之后的state值,我們假設(shè)這就是這個(gè)線程當(dāng)前上下文的一部分內(nèi)容,然后進(jìn)入阻塞等待,一直在while循環(huán)里面等待,如果當(dāng)前線程的Node被添加到了Sync隊(duì)列中去了,那么就可以開始去競(jìng)爭(zhēng)鎖了,否則一直在等待,在await方法的整個(gè)過程中,可以相應(yīng)中斷。

上面分析了await方法,await(long time, TimeUnit unit)方法只是在await方法上加了一個(gè)超時(shí)時(shí)間,await會(huì)死等直到被添加到Sync隊(duì)列中去,而await(long time, TimeUnit unit)方法只會(huì)等設(shè)定的超時(shí)時(shí)間,如果超時(shí)時(shí)間到了,會(huì)自己去競(jìng)爭(zhēng)鎖。

還有awaitUninterruptibly方法是await方法的簡(jiǎn)化版本,它不會(huì)相應(yīng)中斷。awaitUntil(Date deadline)方法讓你可以設(shè)定一個(gè)deadline時(shí)間,如果超過這個(gè)時(shí)間了還沒有被添加到Sync隊(duì)列中去,那么線程就會(huì)自作主張的去競(jìng)爭(zhēng)鎖了。

signal和signalAll方法

上面分析了如何使用await等一系列方法來block線程,現(xiàn)在來分析如何使線程沖破block從而參與到獲取鎖的競(jìng)爭(zhēng)中去。首先分析一下signal方法,使用這個(gè)方法可以使得線程被添加到Sync隊(duì)列中去競(jìng)爭(zhēng)鎖。


        public final void signal() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignal(first);
        }
        
        private void doSignal(Node first) {
            do {
                if ( (firstWaiter = first.nextWaiter) == null)
                    lastWaiter = null;
                first.nextWaiter = null;
            } while (!transferForSignal(first) &&
                     (first = firstWaiter) != null);
        }
        
    final boolean transferForSignal(Node node) {
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
            return false;

        Node p = enq(node);
        int ws = p.waitStatus;
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
            LockSupport.unpark(node.thread);
        return true;
    }
 
    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }          

signal方法首先要喚醒的是等待在它的Condition的等待隊(duì)列上的第一個(gè)節(jié)點(diǎn),signal方法調(diào)用了doSignal方法,而doSignal方法調(diào)用了transferForSignal方法,transferForSignal方法調(diào)用enq方法將節(jié)點(diǎn)添加到了Sync隊(duì)列中去,至此,await方法的while循環(huán)將不滿足繼續(xù)循環(huán)的條件,會(huì)執(zhí)行循環(huán)之后的流程,也就是會(huì)去競(jìng)爭(zhēng)鎖,而之后的流程已經(jīng)在Java同步框架AbstractQueuedSynchronizer中有分析,不在此贅述。

signalAll方法的意思是把所有等待在條件變量上的線程都喚醒去競(jìng)爭(zhēng)鎖,下面是它的流程。


     public final void signalAll() {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            Node first = firstWaiter;
            if (first != null)
                doSignalAll(first);
        }
        
       private void doSignalAll(Node first) {
            lastWaiter = firstWaiter = null;
            do {
                Node next = first.nextWaiter;
                first.nextWaiter = null;
                transferForSignal(first);
                first = next;
            } while (first != null);
        }        

在方法doSignalAll中遍歷每一個(gè)等待在條件變量上的Node,然后調(diào)用transferForSignal方法將它們添加到Sync隊(duì)列中去。關(guān)于Condition的內(nèi)容就分析這么多,介于后文還要對(duì)java的可重入讀寫鎖進(jìn)行分析,所以篇幅不宜過長(zhǎng),日后會(huì)對(duì)Condition進(jìn)行更為深入的學(xué)習(xí)和總結(jié)。

ReentrantReadWriteLock

ReentrantReadWriteLock即可重入讀寫鎖,下文將分析它在什么情況下是可重入的,而在什么情況下是獨(dú)占的。ReentrantReadWriteLock 類實(shí)現(xiàn)了ReadWriteLock接口,它提供的讀寫鎖是分離的,讀鎖和寫鎖分別是獨(dú)立的鎖。而讀鎖和寫鎖的實(shí)現(xiàn)也是不一樣的,ReentrantReadWriteLock使用了兩個(gè)內(nèi)部類ReadLock和WriteLock來分別表示讀鎖和寫鎖,而這兩種鎖又依賴于基于AQS的類Sync來實(shí)現(xiàn),Sync也是一個(gè)內(nèi)部類,它繼承了AQS類來實(shí)現(xiàn)了lock和unlock的語義。首先來分析一下其Sync內(nèi)部類。

Sync內(nèi)部類

首要解決的一個(gè)問題是,我們知道,AQS是使用了一個(gè)int類型的值來表示同步變量的,現(xiàn)在要使用一個(gè)int值來表示讀鎖和寫鎖兩種類型的同步,怎么辦呢?我們知道,一個(gè)int是32位的,ReentrantReadWriteLock使用高16位代表了讀鎖同步變量,而低16位代表了寫鎖同步變量,所以讀鎖與寫鎖的可重入數(shù)量限定在了(2^16-1)個(gè),當(dāng)然AQS還有一個(gè)使用long變量來實(shí)現(xiàn)的版本AbstractQueuedLongSynchronizer,它的實(shí)現(xiàn)和AQS除了使用了long類型的變量來代表同步變量之外沒有區(qū)別。下面我們來看一下Sync是如何獲取重入的讀線程數(shù)量和寫線程數(shù)量的:


        static final int SHARED_SHIFT   = 16;
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

        /** Returns the number of shared holds represented in count  */
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** Returns the number of exclusive holds represented in count  */
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

我們來實(shí)踐一個(gè),比如現(xiàn)在的c是589826,則 (589826 >>> 16 = 9),說明有9個(gè)讀可重入數(shù)量,而(589826 & (1 << 16 - 1)) = 2,說明有寫重入的數(shù)量為2。需要注意的一點(diǎn)是,讀鎖可以有多個(gè)線程獲取,而寫鎖只允許一個(gè)線程獲取,那如何使用16位來代表多個(gè)讀鎖呢?ReentrantReadWriteLock使用了ThreadLocal來保存每個(gè)線程的重入數(shù)量,關(guān)于ThreadLocal的分析總結(jié),可以參考Java中的ThreadLocal和 InheritableThreadLocal,ReentrantReadWriteLock的做法如下:


        /**
         * A counter for per-thread read hold counts.
         * Maintained as a ThreadLocal; cached in cachedHoldCounter
         */
        static final class HoldCounter {
            int count = 0;
            // Use id, not reference, to avoid garbage retention
            final long tid = getThreadId(Thread.currentThread());
        }

        /**
         * ThreadLocal subclass. Easiest to explicitly define for sake
         * of deserialization mechanics.
         */
        static final class ThreadLocalHoldCounter
            extends ThreadLocal<HoldCounter> {
            public HoldCounter initialValue() {
                return new HoldCounter();
            }
        }

    private transient HoldCounter cachedHoldCounter;
    

Sync類實(shí)現(xiàn)了一些子類通用了方法,下面重點(diǎn)分析幾個(gè)方法。

tryRelease和tryReleaseShared方法

tryRelease方法重寫了AQS的tryRelease方法,而tryRelease這個(gè)方法會(huì)在release方法中使用到,也就是在unlock的時(shí)候用到。下面展示了它的細(xì)節(jié):


        protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;
            boolean free = exclusiveCount(nextc) == 0;
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }

tryRelease很好理解,它的任務(wù)就是去更新state值,它調(diào)用了我們上面分析過的exclusiveCount方法來計(jì)算寫重入的數(shù)量。到這里需要提出的是,ReentrantReadWriteLock在實(shí)現(xiàn)上實(shí)現(xiàn)了讀鎖和寫鎖,讀鎖允許多個(gè)線程重入,使用了AQS的共享模式,而寫鎖只允許一個(gè)線程獲得鎖,使用了AQS的獨(dú)占模式,所以這個(gè)tryRelease方法會(huì)在WriteLock的unlock方法中被用到,而ReadLock中的unlock使用的是AQS的releaseShared方法,而這個(gè)方法會(huì)調(diào)用AQS的tryReleaseShared方法,而這個(gè)方法在Sync被重寫,也就是接下來分析的方法:


        protected final boolean tryReleaseShared(int unused) {
            Thread current = Thread.currentThread();
            if (firstReader == current) {
                // assert firstReaderHoldCount > 0;
                if (firstReaderHoldCount == 1)
                    firstReader = null;
                else
                    firstReaderHoldCount--;
            } else {
                HoldCounter rh = cachedHoldCounter;
                if (rh == null || rh.tid != getThreadId(current))
                    rh = readHolds.get();
                int count = rh.count;
                if (count <= 1) {
                    readHolds.remove();
                    if (count <= 0)
                        throw unmatchedUnlockException();
                }
                --rh.count;
            }
            for (;;) {
                int c = getState();
                int nextc = c - SHARED_UNIT;
                if (compareAndSetState(c, nextc))
                    // Releasing the read lock has no effect on readers,
                    // but it may allow waiting writers to proceed if
                    // both read and write locks are now free.
                    return nextc == 0;
            }
        }

可以很明顯的感覺得出來,讀鎖的釋放要比寫鎖的釋放要麻煩很多,因?yàn)閷戞i只有一個(gè)線程獲得,而讀鎖則有多個(gè)線程獲取。釋放需要獲取到當(dāng)前線程的ThreadLocal變量,然后更新它的重入數(shù)量,更新state值。可以看到,因?yàn)槭褂昧薚hreadLocal,使得多個(gè)線程的問題變得簡(jiǎn)單起來,就好像是操作同一個(gè)線程一樣。

tryAcquire和tryAcquireShared方法

ReadLock在調(diào)用lock方法的時(shí)候,會(huì)調(diào)用AQS的releaseShared方法,而releaseShared方法會(huì)調(diào)用AQS的tryReleaseShared方法,而tryReleaseShared方法在Sync中被重寫了。WriteLock在lock的時(shí)候,會(huì)調(diào)用AQS的acquire方法,而acquire方法會(huì)調(diào)用AQS的tryAcquire方法,而tryAcquire方法在Sync中被重寫了,所以接下來分析一下這兩個(gè)被重寫的方法來認(rèn)識(shí)一下WriteLock和ReadLock是如何通過AQS來lock的。

首先是tryAcquire方法:


        protected final boolean tryAcquire(int acquires) {
            /*
             * Walkthrough:
             * 1. If read count nonzero or write count nonzero
             *    and owner is a different thread, fail.
             * 2. If count would saturate, fail. (This can only
             *    happen if count is already nonzero.)
             * 3. Otherwise, this thread is eligible for lock if
             *    it is either a reentrant acquire or
             *    queue policy allows it. If so, update state
             *    and set owner.
             */
            Thread current = Thread.currentThread();
            int c = getState();
            int w = exclusiveCount(c);
            if (c != 0) {
                // (Note: if c != 0 and w == 0 then shared count != 0)
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire
                setState(c + acquires);
                return true;
            }
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }

這個(gè)方法用于寫鎖上鎖,我們知道,只有一個(gè)線程可以獲取到寫鎖,如果w為0,說明已經(jīng)有線程獲得了讀鎖,而在有讀線程在讀取數(shù)據(jù)的時(shí)候,寫鎖是無法獲得的,所以w為0直接回失敗,或者w不為0則說明了已經(jīng)有線程獲得了寫鎖,那么因?yàn)橹辉试S有一個(gè)線程獲取到寫鎖,所以如果當(dāng)前線程不是那個(gè)獲得了寫鎖的獨(dú)占鎖的話,也就直接失敗,否則,如果上面兩條檢測(cè)都通過了,也就是說,當(dāng)前沒有線程獲得讀鎖和寫鎖,那么判斷重入數(shù)量是否超過了最大值,如果是則拋出異常,否則上鎖成功。上面的分析都是基于c不為0,也就是說已經(jīng)有線程獲得了讀鎖或者寫鎖的情況下分析的,那如果c為0呢?說明當(dāng)前環(huán)境下沒有線程占有鎖,那么接下來就分公平鎖和非公平鎖了,Sync有兩個(gè)抽象方法需要子類來實(shí)現(xiàn)為公平鎖還是非公平鎖:


        /**
         * Returns true if the current thread, when trying to acquire
         * the read lock, and otherwise eligible to do so, should block
         * because of policy for overtaking other waiting threads.
         */
        abstract boolean readerShouldBlock();

        /**
         * Returns true if the current thread, when trying to acquire
         * the write lock, and otherwise eligible to do so, should block
         * because of policy for overtaking other waiting threads.
         */
        abstract boolean writerShouldBlock();

具體的細(xì)節(jié)到公平鎖和非公平鎖的分析上再講細(xì)節(jié)。上面分析完了WriteLock使用的lock需要的tryAcquire方法,下面來分析一下ReadLock的lock需要的tryReleaseShared方法:


        protected final int tryAcquireShared(int unused) {
            /*
             * Walkthrough:
             * 1. If write lock held by another thread, fail.
             * 2. Otherwise, this thread is eligible for
             *    lock wrt state, so ask if it should block
             *    because of queue policy. If not, try
             *    to grant by CASing state and updating count.
             *    Note that step does not check for reentrant
             *    acquires, which is postponed to full version
             *    to avoid having to check hold count in
             *    the more typical non-reentrant case.
             * 3. If step 2 fails either because thread
             *    apparently not eligible or CAS fails or count
             *    saturated, chain to version with full retry loop.
             */
            Thread current = Thread.currentThread();
            int c = getState();
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            int r = sharedCount(c);
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                compareAndSetState(c, c + SHARED_UNIT)) {
                if (r == 0) {
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (firstReader == current) {
                    firstReaderHoldCount++;
                } else {
                    HoldCounter rh = cachedHoldCounter;
                    if (rh == null || rh.tid != getThreadId(current))
                        cachedHoldCounter = rh = readHolds.get();
                    else if (rh.count == 0)
                        readHolds.set(rh);
                    rh.count++;
                }
                return 1;
            }
            return fullTryAcquireShared(current);
        }

同樣比WriteLock的要復(fù)雜很多,這個(gè)方法會(huì)返回1或者-1代表lock的結(jié)果,1代表lock成功了,-1代表lock失敗了,來分析一下在上面情況下會(huì)失敗:

1、如果有線程已經(jīng)獲得了寫鎖,那么肯定會(huì)失敗,因?yàn)閷戞i是排斥鎖,不允許其他線程獲得任意類型的鎖
2、如果重入的數(shù)量已經(jīng)超過了限定,那么也會(huì)失敗,如果你還想要支持更多的重入數(shù)量,那么使用AbstractQueuedLongSynchronizer來代替AQS

而在下面的情況下是會(huì)成功的:

1、沒有線程獲得寫鎖
2、獲得寫鎖的線程就是當(dāng)前想要獲得讀鎖的線程
3、重入數(shù)量沒有超過上限

總結(jié)起來就是,只要有線程獲得了寫鎖,那么其他線程都獲取不到寫鎖,如果獲得寫鎖的線程想要獲取讀鎖,那么可以成功。在獲取讀鎖的時(shí)候,多個(gè)線程可以同時(shí)獲得讀鎖,讀鎖是共享鎖,而寫鎖是獨(dú)占鎖。

FairSync和NonFairSync的實(shí)現(xiàn)

這兩個(gè)類僅僅是繼承了父類然后實(shí)現(xiàn)了兩個(gè)抽象方法,來表示讀線程是否需要阻塞和寫線程是否需要阻塞,以這樣的方式來達(dá)到公平鎖和非公平鎖的目的。

下面是公平鎖的實(shí)現(xiàn):


        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }

可以看出,對(duì)于公平鎖來說,讀鎖和寫鎖都是查看Sync隊(duì)列中是否有排隊(duì)的線程,如果沒有,則可以放行,否則就得排隊(duì)。下面是非公平鎖的實(shí)現(xiàn):



       final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
        final boolean readerShouldBlock() {
            /* As a heuristic to avoid indefinite writer starvation,
             * block if the thread that momentarily appears to be head
             * of queue, if one exists, is a waiting writer.  This is
             * only a probabilistic effect since a new reader will not
             * block if there is a waiting writer behind other enabled
             * readers that have not yet drained from the queue.
             */
            return apparentlyFirstQueuedIsExclusive();
        }

    final boolean apparentlyFirstQueuedIsExclusive() {
        Node h, s;
        return (h = head) != null &&
            (s = h.next)  != null &&
            !s.isShared()         &&
            s.thread != null;
    }

在非公平鎖中,寫鎖的獲取不需要阻塞,而讀鎖的獲取在apparentlyFirstQueuedIsExclusive中判斷是否需要阻塞。所謂公平鎖和非公平鎖只是希望能對(duì)所有的線程都不區(qū)別對(duì)待,但是使用公平鎖的代價(jià)是吞吐量沒有非公平鎖那么大,所以,如果我們的需求沒有特別的原因,應(yīng)該使用非公平鎖。

ReadLock和WriteLock

上面介紹了Sync類,現(xiàn)在來分析一下ReadLock和WriteLock是如何通過Sync提高的方法來實(shí)現(xiàn)lock和unlock的。首先是ReadLock。它的lock和unlock方法如下:


       public void lock() {
            sync.acquireShared(1);
        }

        public void unlock() {
            sync.releaseShared(1);
        }

而WriteLock的lock和unlock方法如下:


        public void lock() {
            sync.acquire(1);
        }

        public void unlock() {
            sync.release(1);
        }

如果想要獲取更多關(guān)于AQS的相關(guān)知識(shí),可以去閱讀AQS的源代碼,或者參考Java同步框架AbstractQueuedSynchronizer,上文中也對(duì)lock和unlock的流程有所分析,再次也不做贅述。

可重入鎖使用示例

最后,在分析了ReentrantLock和ReentrantReadWriteLock之后,來看一下如何使用它們。

ReentrantLock使用示例


/**
 * how to use ReentrantLock lock
 */
class LockX {
    private final Lock LOCK = new ReentrantLock(); // non-fair lock
    
    public void lockMethod() {
        LOCK.lock();
        try {
            doBiz();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            LOCK.unlock();
        }
    }
    
    public void doBiz() {
        
    }
    
}

你需要注意的是你應(yīng)該總是在try塊中執(zhí)行你的業(yè)務(wù)代碼,然后在finally中unlock掉。

ReentrantReadWriteLock使用示例


abstract class CachedData {
    Object data;
    volatile boolean cacheValid;
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    
    void processCachedData() {
      rwl.readLock().lock();
      if (!cacheValid) {
        // Must release read lock before acquiring write lock
        rwl.readLock().unlock();
        rwl.writeLock().lock();
        try {
          // Recheck state because another thread might have
          // acquired write lock and changed state before we did.
          if (!cacheValid) {
            data = loadData();
            cacheValid = true;
          }
          // Downgrade by acquiring read lock before releasing write lock
          rwl.readLock().lock();
        } finally {
          rwl.writeLock().unlock(); // Unlock write, still hold read
        }
      }
 
      try {
        consumeData(data);
      } finally {
        rwl.readLock().unlock();
      }
    }
    
    abstract Object loadData();
    abstract void consumeData(Object data);
  }

別忘了在lock之后要unlock,否則如果一個(gè)寫鎖被獲取之后沒有釋放的話,就不可能有鎖獲得鎖了除非它自己本身。通用的做法是在try 塊中進(jìn)行業(yè)務(wù)處理,然后在finally中釋放鎖。Lock接口的使用相比于synchronized的使用要復(fù)雜很多,所以在大部分情況下,你應(yīng)該使用synchronized來做并發(fā)控制,而不是Lock,但是如果想要做更加靈活的鎖控制,你就可以選擇使用Lock接口的具體實(shí)現(xiàn)類來應(yīng)用,或者繼承AQS來實(shí)現(xiàn)自己的同步器。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 摘要: 我們已經(jīng)知道,synchronized 是Java的關(guān)鍵字,是Java的內(nèi)置特性,在JVM層面實(shí)現(xiàn)了對(duì)臨界...
    kingZXY2009閱讀 1,845評(píng)論 0 20
  • 一、 概述 本文首先介紹Lock接口、ReentrantLock的類層次結(jié)構(gòu)以及鎖功能模板類AbstractQue...
    等一夏_81f7閱讀 770評(píng)論 0 0
  • 京東小金庫(kù)的收益結(jié)算方式是怎樣的?
    麗江理閱讀 252評(píng)論 1 0
  • 10分鐘入門已經(jīng)寫完了,那么基本的東西大概都了解。入門以后我們的目標(biāo)變成了要玩的6,666666666666666...
    default閱讀 1,973評(píng)論 0 1