成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專(zhuān)欄INFORMATION COLUMN

Java并發(fā)核心淺談(二)

Null / 1194人閱讀

摘要:在線程處理任務(wù)期間,其它線程要么循環(huán)訪問(wèn),要么一直阻塞等著線程喚醒,再不濟(jì)就真的如我所說(shuō),放棄鎖的競(jìng)爭(zhēng),去處理別的任務(wù)。寫(xiě)鎖的話,獨(dú)占寫(xiě)計(jì)數(shù),排除一切其他線程。

回顧

在上一篇 Java并發(fā)核心淺談 我們大概了解到了Locksynchronized的共同點(diǎn),再簡(jiǎn)單總結(jié)下:

Lock主要是自定義一個(gè) counter,從而利用CAS對(duì)其實(shí)現(xiàn)原子操作,而synchronizedc++ hotspot實(shí)現(xiàn)的 monitor(具體的咱也沒(méi)看,咱就不說(shuō))

二者都可重入(遞歸,互調(diào),循環(huán)),其本質(zhì)都是維護(hù)一個(gè)可計(jì)數(shù)的 counter,在其它線程訪問(wèn)加鎖對(duì)象時(shí)會(huì)判斷 counter 是否為 0

理論上講二者都是阻塞式的,因?yàn)榫€程在拿鎖時(shí),如果拿不到,最終的結(jié)果只能等待(前提是線程的最終目的就是要獲取鎖)讀寫(xiě)鎖分離成兩把鎖了,所以不一樣

舉個(gè)例子:線程 A 持有了某個(gè)對(duì)象的 monitor,其它線程在訪問(wèn)該對(duì)象時(shí),發(fā)現(xiàn) monitor 不為 0,所以只能阻塞掛起或者加入等待隊(duì)列,等著線程 A 處理完退出后將 monitor 置為 0。在線程 A 處理任務(wù)期間,其它線程要么循環(huán)訪問(wèn) monitor,要么一直阻塞等著線程 A 喚醒,再不濟(jì)就真的如我所說(shuō),放棄鎖的競(jìng)爭(zhēng),去處理別的任務(wù)。但是應(yīng)該做不到去處理別的任務(wù)后,任務(wù)處理到一半,被線程 A 通知后再回去搶鎖

公平鎖與非公平鎖

不共享 counter

        // 非公平鎖在第一次拿鎖失敗也會(huì)調(diào)用該方法
        public final void acquire(int arg) {
        // 沒(méi)拿到鎖就加入隊(duì)列
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
        }
        
        // 非公平鎖方法
        final void lock() {
            // 走來(lái)就嘗試獲取鎖
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1); // 上面那個(gè)方法
        }
        
        // 公平鎖 Acquire 計(jì)數(shù)
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            // 拿到計(jì)數(shù)
            int c = getState();
            if (c == 0) {
                // 公平鎖會(huì)先嘗試排隊(duì) 非公平鎖少個(gè) !hasQueuedPredecessors() 其它代碼一樣
                if (!hasQueuedPredecessors() &&
                    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;
        }
        
        /**
         * @return {@code true} if there is a queued thread preceding the // 當(dāng)前線程前有線程等待,則排隊(duì)
         *         current thread, and {@code false} if the current thread
         *         is at the head of the queue or the queue is empty // 隊(duì)列為空不用排隊(duì)
         * @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;
            // 當(dāng)前線程處于頭節(jié)點(diǎn)的下一個(gè)且不為空則不用排隊(duì)
            // 或該線程就是當(dāng)前持有鎖的線程,即重入鎖,也不用排隊(duì)
            return h != t &&
                ((s = h.next) == null || s.thread != Thread.currentThread());
        }
        
        // 加入等待隊(duì)列
        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;
                }
                // 獲取失敗會(huì)檢查節(jié)點(diǎn)狀態(tài)
                // 然后 park 線程
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
        /** waitStatus value to indicate thread has cancelled */
        static final int CANCELLED =  1; // 線程取消加鎖
        /** waitStatus value to indicate successor"s thread needs unparking */
        static final int SIGNAL    = -1;  // 解除線程 park
        /** waitStatus value to indicate thread is waiting on condition */ // 
        static final int CONDITION = -2; // 線程被阻塞
        /**
         * waitStatus value to indicate the next acquireShared should
         * unconditionally propagate
         */
        static final int PROPAGATE = -3; // 廣播
        
        // 官方注釋
        /**
         * Status field, taking on only the values:
         *   SIGNAL:     The successor of this node is (or will soon be)
         *               blocked (via park), so the current node must
         *               unpark its successor when it releases or
         *               cancels. To avoid races, acquire methods must
         *               first indicate they need a signal,
         *               then retry the atomic acquire, and then,
         *               on failure, block.
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
         *               Nodes never leave this state. In particular,
         *               a thread with cancelled node never again blocks.
         *   CONDITION:  This node is currently on a condition queue.
         *               It will not be used as a sync queue node
         *               until transferred, at which time the status
         *               will be set to 0. (Use of this value here has
         *               nothing to do with the other uses of the
         *               field, but simplifies mechanics.)
         *   PROPAGATE:  A releaseShared should be propagated to other
         *               nodes. This is set (for head node only) in
         *               doReleaseShared to ensure propagation
         *               continues, even if other operations have
         *               since intervened.
         *   0:          None of the above
         *
         * The values are arranged numerically to simplify use.
         * Non-negative values mean that a node doesn"t need to
         * signal. So, most code doesn"t need to check for particular
         * values, just for sign.
         *
         * The field is initialized to 0 for normal sync nodes, and
         * CONDITION for condition nodes.  It is modified using CAS
         * (or when possible, unconditional volatile writes).
         */
        volatile int waitStatus;
讀鎖與寫(xiě)鎖(共享鎖與排他鎖)

讀鎖:共享 counter

寫(xiě)鎖:不共享 counter

        // 讀寫(xiě)鎖和線程池的類(lèi)似之處
        // 高 16 位為讀計(jì)數(shù),低 16 位為寫(xiě)計(jì)數(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. */ // 獲取讀計(jì)數(shù)
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** Returns the number of exclusive holds represented in count. */ // 獲取寫(xiě)計(jì)數(shù)
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
        
        /**
         * A counter for per-thread read hold counts. 每個(gè)線程自己的讀計(jì)數(shù)
         * Maintained as a ThreadLocal; cached in cachedHoldCounter.
         */
        static final class HoldCounter {
            int count;          // initially 0
            // Use id, not reference, to avoid garbage retention
            final long tid = LockSupport.getThreadId(Thread.currentThread()); // 線程 id
        }
        
    // 嘗試獲取讀鎖
    protected final int tryAcquireShared(int unused) {
            // ReentrantReadWriteLock ReadLock 讀鎖
            /*
             * 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();
            // 如果寫(xiě)鎖計(jì)數(shù)不為零,且當(dāng)前線程不是寫(xiě)鎖持有線程,則可以獲得讀鎖
            // 言外之意,獲得寫(xiě)鎖的線程不可以再獲得讀鎖
            // 個(gè)人認(rèn)為不用判斷寫(xiě)計(jì)數(shù)也行
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            // 獲得讀計(jì)數(shù)
            int r = sharedCount(c);
            // 檢查等待隊(duì)列 讀計(jì)數(shù)上限
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                // 在高 16 位更新
                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 != LockSupport.getThreadId(current))
                        // cachedHoldCounter 每個(gè)線程自己的讀計(jì)數(shù),非共享。但是鎖計(jì)數(shù)與其它讀操作共享,不與寫(xiě)操作共享
                        // readHolds 為T(mén)hreadLocalHoldCounter,繼承于 ThreadLocal,存 cachedHoldCounter
                        cachedHoldCounter = rh = readHolds.get();
                    else if (rh.count == 0)
                        readHolds.set(rh);
                    rh.count++;
                }
                return 1;
            }
            // 說(shuō)明在排隊(duì)中,就一直遍歷,直到隊(duì)首,實(shí)際起作用的代碼和上面代碼差不多
            // 大師本人也說(shuō)了代碼有冗余
             /*
             * This code is in part redundant with that in
             * tryAcquireShared but is simpler overall by not
             * complicating tryAcquireShared with interactions between
             * retries and lazily reading hold counts.
             */
            return fullTryAcquireShared(current);
        }
        
    // 獲得寫(xiě)鎖  
    protected final boolean tryAcquire(int acquires) {
            /*
             * Walkthrough:
             * 1. If read count nonzero or write count nonzero
             *    and owner is a different thread, fail. 
             * 讀鎖不為零(讀鎖排除寫(xiě)鎖,但是與讀鎖共享)
             * 寫(xiě)鎖不為零且鎖持有者不為當(dāng)前線程,則獲得鎖失敗
             * 2. If count would saturate, fail. (This can only
             *    happen if count is already nonzero.) // 計(jì)數(shù)器已達(dá)最大值,獲得鎖失敗
             * 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. // 重入是可以的;隊(duì)列策略也是可以的,會(huì)在下面解釋
             */
            Thread current = Thread.currentThread();
            int c = getState();
            // 獲得寫(xiě)計(jì)數(shù)
            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;
                // 檢查最大計(jì)數(shù)
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // Reentrant acquire 線程重入獲得鎖,直接更新計(jì)數(shù)
                setState(c + acquires);
                return true;
            }
            // 隊(duì)列策略
            // state 為 0,檢查是否需要排隊(duì)
            // 針對(duì)公平鎖:去排隊(duì),如果當(dāng)前線程在隊(duì)首或等待隊(duì)列為空,則返回 false,自然會(huì)走后面的 CAS
            // 否則就返回 true,則進(jìn)入 return false;
            // 針對(duì)非公平鎖:寫(xiě)死為 false,直接 CAS
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            // 設(shè)置當(dāng)前寫(xiě)鎖持有線程
            setExclusiveOwnerThread(current);
            return true;
        }    
    
    // 因?yàn)樽x鎖是多個(gè)線程共享讀計(jì)數(shù),各自維護(hù)了自己的讀計(jì)數(shù),所以釋放的時(shí)候比寫(xiě)鎖釋放要多些操作
     protected final boolean tryReleaseShared(int unused) {
            Thread current = Thread.currentThread();
            // 當(dāng)前線程是第一讀線程的操作
            // firstReader 作為字段緩存,是考慮到第一次讀的線程使用率高?
            if (firstReader == current) {
                // assert firstReaderHoldCount > 0;
                if (firstReaderHoldCount == 1)
                    firstReader = null;
                else
                    firstReaderHoldCount--;
            } else {
                HoldCounter rh = cachedHoldCounter;
                if (rh == null ||
                    rh.tid != LockSupport.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;
            }
        }
總結(jié)一下

公平鎖和非公平鎖的“鎖”實(shí)現(xiàn)是基于CAS,公平性基于內(nèi)部維護(hù)的Node鏈表

讀寫(xiě)鎖,可以粗略的理解為讀和寫(xiě)兩種狀態(tài),所以這兒的設(shè)計(jì)類(lèi)似線程池的狀態(tài)。只不過(guò),讀計(jì)數(shù)是可以多個(gè)讀線程共享的(排除寫(xiě)鎖),每個(gè)讀的線程都會(huì)維護(hù)自己的讀計(jì)數(shù)。寫(xiě)鎖的話,獨(dú)占寫(xiě)計(jì)數(shù),排除一切其他線程。

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/77772.html

相關(guān)文章

  • Java并發(fā)核心淺談

    摘要:耐心看完的你或多或少會(huì)有收獲并發(fā)的核心就是包,而的核心是抽象隊(duì)列同步器,簡(jiǎn)稱(chēng),一些鎖啊信號(hào)量啊循環(huán)屏障啊都是基于。 耐心看完的你或多或少會(huì)有收獲! Java并發(fā)的核心就是 java.util.concurrent 包,而 j.u.c 的核心是AbstractQueuedSynchronizer抽象隊(duì)列同步器,簡(jiǎn)稱(chēng) AQS,一些鎖??!信號(hào)量?。⊙h(huán)屏障??!都是基于AQS。而 AQS 又是...

    cppowboy 評(píng)論0 收藏0
  • 淺談Java并發(fā)編程系列()—— Java內(nèi)存模型

    摘要:物理計(jì)算機(jī)并發(fā)問(wèn)題在介紹內(nèi)存模型之前,先簡(jiǎn)單了解下物理計(jì)算機(jī)中的并發(fā)問(wèn)題?;诟咚倬彺娴拇鎯?chǔ)交互引入一個(gè)新的問(wèn)題緩存一致性。寫(xiě)入作用于主內(nèi)存變量,把操作從工作內(nèi)存中得到的變量值放入主內(nèi)存的變量中。 物理計(jì)算機(jī)并發(fā)問(wèn)題 在介紹Java內(nèi)存模型之前,先簡(jiǎn)單了解下物理計(jì)算機(jī)中的并發(fā)問(wèn)題。由于處理器的與存儲(chǔ)設(shè)置的運(yùn)算速度有幾個(gè)數(shù)量級(jí)的差距,所以現(xiàn)代計(jì)算機(jī)加入一層讀寫(xiě)速度盡可能接近處理器的高速緩...

    Edison 評(píng)論0 收藏0
  • 淺談Java并發(fā)編程系列(一)—— 如何保證線程安全

    摘要:比如需要用多線程或分布式集群統(tǒng)計(jì)一堆用戶的相關(guān)統(tǒng)計(jì)值,由于用戶的統(tǒng)計(jì)值是共享數(shù)據(jù),因此需要保證線程安全。如果類(lèi)是無(wú)狀態(tài)的,那它永遠(yuǎn)是線程安全的。參考探索并發(fā)編程二寫(xiě)線程安全的代碼 線程安全類(lèi) 保證類(lèi)線程安全的措施: 不共享線程間的變量; 設(shè)置屬性變量為不可變變量; 每個(gè)共享的可變變量都使用一個(gè)確定的鎖保護(hù); 保證線程安全的思路: 1. 通過(guò)架構(gòu)設(shè)計(jì) 通過(guò)上層的架構(gòu)設(shè)計(jì)和業(yè)務(wù)分析來(lái)避...

    mylxsw 評(píng)論0 收藏0
  • 淺談Java并發(fā)編程系列(六) —— 線程池的使用

    摘要:線程池的作用降低資源消耗。通過(guò)重復(fù)利用已創(chuàng)建的線程降低線程創(chuàng)建和銷(xiāo)毀造成的資源浪費(fèi)。而高位的部分,位表示線程池的狀態(tài)。當(dāng)線程池中的線程數(shù)達(dá)到后,就會(huì)把到達(dá)的任務(wù)放到中去線程池的最大長(zhǎng)度。默認(rèn)情況下,只有當(dāng)線程池中的線程數(shù)大于時(shí),才起作用。 線程池的作用 降低資源消耗。通過(guò)重復(fù)利用已創(chuàng)建的線程降低線程創(chuàng)建和銷(xiāo)毀造成的資源浪費(fèi)。 提高響應(yīng)速度。當(dāng)任務(wù)到達(dá)時(shí),不需要等到線程創(chuàng)建就能立即執(zhí)行...

    Vicky 評(píng)論0 收藏0
  • 后臺(tái)開(kāi)發(fā)常問(wèn)面試題集錦(問(wèn)題搬運(yùn)工,附鏈接)

    摘要:基礎(chǔ)問(wèn)題的的性能及原理之區(qū)別詳解備忘筆記深入理解流水線抽象關(guān)鍵字修飾符知識(shí)點(diǎn)總結(jié)必看篇中的關(guān)鍵字解析回調(diào)機(jī)制解讀抽象類(lèi)與三大特征時(shí)間和時(shí)間戳的相互轉(zhuǎn)換為什么要使用內(nèi)部類(lèi)對(duì)象鎖和類(lèi)鎖的區(qū)別,,優(yōu)缺點(diǎn)及比較提高篇八詳解內(nèi)部類(lèi)單例模式和 Java基礎(chǔ)問(wèn)題 String的+的性能及原理 java之yield(),sleep(),wait()區(qū)別詳解-備忘筆記 深入理解Java Stream流水...

    spacewander 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<