摘要:在線程處理任務(wù)期間,其它線程要么循環(huán)訪問,要么一直阻塞等著線程喚醒,再不濟就真的如我所說,放棄鎖的競爭,去處理別的任務(wù)。寫鎖的話,獨占寫計數(shù),排除一切其他線程。
回顧
在上一篇 Java并發(fā)核心淺談 我們大概了解到了Lock和synchronized的共同點,再簡單總結(jié)下:
Lock主要是自定義一個 counter,從而利用CAS對其實現(xiàn)原子操作,而synchronized是c++ hotspot實現(xiàn)的 monitor(具體的咱也沒看,咱就不說)
二者都可重入(遞歸,互調(diào),循環(huán)),其本質(zhì)都是維護一個可計數(shù)的 counter,在其它線程訪問加鎖對象時會判斷 counter 是否為 0
理論上講二者都是阻塞式的,因為線程在拿鎖時,如果拿不到,最終的結(jié)果只能等待(前提是線程的最終目的就是要獲取鎖)讀寫鎖分離成兩把鎖了,所以不一樣
舉個例子:線程 A 持有了某個對象的 monitor,其它線程在訪問該對象時,發(fā)現(xiàn) monitor 不為 0,所以只能阻塞掛起或者加入等待隊列,等著線程 A 處理完退出后將 monitor 置為 0。在線程 A 處理任務(wù)期間,其它線程要么循環(huán)訪問 monitor,要么一直阻塞等著線程 A 喚醒,再不濟就真的如我所說,放棄鎖的競爭,去處理別的任務(wù)。但是應(yīng)該做不到去處理別的任務(wù)后,任務(wù)處理到一半,被線程 A 通知后再回去搶鎖
公平鎖與非公平鎖不共享 counter
// 非公平鎖在第一次拿鎖失敗也會調(diào)用該方法 public final void acquire(int arg) { // 沒拿到鎖就加入隊列 if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) selfInterrupt(); } // 非公平鎖方法 final void lock() { // 走來就嘗試獲取鎖 if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); // 上面那個方法 } // 公平鎖 Acquire 計數(shù) protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); // 拿到計數(shù) int c = getState(); if (c == 0) { // 公平鎖會先嘗試排隊 非公平鎖少個 !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 // 當前線程前有線程等待,則排隊 * 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; // 當前線程處于頭節(jié)點的下一個且不為空則不用排隊 // 或該線程就是當前持有鎖的線程,即重入鎖,也不用排隊 return h != t && ((s = h.next) == null || s.thread != Thread.currentThread()); } // 加入等待隊列 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; } // 獲取失敗會檢查節(jié)點狀態(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;讀鎖與寫鎖(共享鎖與排他鎖)
讀鎖:共享 counter
寫鎖:不共享 counter
// 讀寫鎖和線程池的類似之處 // 高 16 位為讀計數(shù),低 16 位為寫計數(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. */ // 獲取讀計數(shù) static int sharedCount(int c) { return c >>> SHARED_SHIFT; } /** Returns the number of exclusive holds represented in count. */ // 獲取寫計數(shù) static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; } /** * A counter for per-thread read hold counts. 每個線程自己的讀計數(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(); // 如果寫鎖計數(shù)不為零,且當前線程不是寫鎖持有線程,則可以獲得讀鎖 // 言外之意,獲得寫鎖的線程不可以再獲得讀鎖 // 個人認為不用判斷寫計數(shù)也行 if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; // 獲得讀計數(shù) int r = sharedCount(c); // 檢查等待隊列 讀計數(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 每個線程自己的讀計數(shù),非共享。但是鎖計數(shù)與其它讀操作共享,不與寫操作共享 // readHolds 為ThreadLocalHoldCounter,繼承于 ThreadLocal,存 cachedHoldCounter cachedHoldCounter = rh = readHolds.get(); else if (rh.count == 0) readHolds.set(rh); rh.count++; } return 1; } // 說明在排隊中,就一直遍歷,直到隊首,實際起作用的代碼和上面代碼差不多 // 大師本人也說了代碼有冗余 /* * 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); } // 獲得寫鎖 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.) // 計數(shù)器已達最大值,獲得鎖失敗 * 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(); // 獲得寫計數(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; // 檢查最大計數(shù) if (w + exclusiveCount(acquires) > MAX_COUNT) throw new Error("Maximum lock count exceeded"); // Reentrant acquire 線程重入獲得鎖,直接更新計數(shù) setState(c + acquires); return true; } // 隊列策略 // state 為 0,檢查是否需要排隊 // 針對公平鎖:去排隊,如果當前線程在隊首或等待隊列為空,則返回 false,自然會走后面的 CAS // 否則就返回 true,則進入 return false; // 針對非公平鎖:寫死為 false,直接 CAS if (writerShouldBlock() || !compareAndSetState(c, c + acquires)) return false; // 設(shè)置當前寫鎖持有線程 setExclusiveOwnerThread(current); return true; } // 因為讀鎖是多個線程共享讀計數(shù),各自維護了自己的讀計數(shù),所以釋放的時候比寫鎖釋放要多些操作 protected final boolean tryReleaseShared(int unused) { Thread current = Thread.currentThread(); // 當前線程是第一讀線程的操作 // 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é)一下
公平鎖和非公平鎖的“鎖”實現(xiàn)是基于CAS,公平性基于內(nèi)部維護的Node鏈表
讀寫鎖,可以粗略的理解為讀和寫兩種狀態(tài),所以這兒的設(shè)計類似線程池的狀態(tài)。只不過,讀計數(shù)是可以多個讀線程共享的(排除寫鎖),每個讀的線程都會維護自己的讀計數(shù)。寫鎖的話,獨占寫計數(shù),排除一切其他線程。
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://m.hztianpu.com/yun/77772.html
摘要:耐心看完的你或多或少會有收獲并發(fā)的核心就是包,而的核心是抽象隊列同步器,簡稱,一些鎖啊信號量啊循環(huán)屏障啊都是基于。 耐心看完的你或多或少會有收獲! Java并發(fā)的核心就是 java.util.concurrent 包,而 j.u.c 的核心是AbstractQueuedSynchronizer抽象隊列同步器,簡稱 AQS,一些鎖??!信號量??!循環(huán)屏障啊!都是基于AQS。而 AQS 又是...
摘要:物理計算機并發(fā)問題在介紹內(nèi)存模型之前,先簡單了解下物理計算機中的并發(fā)問題?;诟咚倬彺娴拇鎯换ヒ胍粋€新的問題緩存一致性。寫入作用于主內(nèi)存變量,把操作從工作內(nèi)存中得到的變量值放入主內(nèi)存的變量中。 物理計算機并發(fā)問題 在介紹Java內(nèi)存模型之前,先簡單了解下物理計算機中的并發(fā)問題。由于處理器的與存儲設(shè)置的運算速度有幾個數(shù)量級的差距,所以現(xiàn)代計算機加入一層讀寫速度盡可能接近處理器的高速緩...
摘要:比如需要用多線程或分布式集群統(tǒng)計一堆用戶的相關(guān)統(tǒng)計值,由于用戶的統(tǒng)計值是共享數(shù)據(jù),因此需要保證線程安全。如果類是無狀態(tài)的,那它永遠是線程安全的。參考探索并發(fā)編程二寫線程安全的代碼 線程安全類 保證類線程安全的措施: 不共享線程間的變量; 設(shè)置屬性變量為不可變變量; 每個共享的可變變量都使用一個確定的鎖保護; 保證線程安全的思路: 1. 通過架構(gòu)設(shè)計 通過上層的架構(gòu)設(shè)計和業(yè)務(wù)分析來避...
摘要:線程池的作用降低資源消耗。通過重復(fù)利用已創(chuàng)建的線程降低線程創(chuàng)建和銷毀造成的資源浪費。而高位的部分,位表示線程池的狀態(tài)。當線程池中的線程數(shù)達到后,就會把到達的任務(wù)放到中去線程池的最大長度。默認情況下,只有當線程池中的線程數(shù)大于時,才起作用。 線程池的作用 降低資源消耗。通過重復(fù)利用已創(chuàng)建的線程降低線程創(chuàng)建和銷毀造成的資源浪費。 提高響應(yīng)速度。當任務(wù)到達時,不需要等到線程創(chuàng)建就能立即執(zhí)行...
摘要:基礎(chǔ)問題的的性能及原理之區(qū)別詳解備忘筆記深入理解流水線抽象關(guān)鍵字修飾符知識點總結(jié)必看篇中的關(guān)鍵字解析回調(diào)機制解讀抽象類與三大特征時間和時間戳的相互轉(zhuǎn)換為什么要使用內(nèi)部類對象鎖和類鎖的區(qū)別,,優(yōu)缺點及比較提高篇八詳解內(nèi)部類單例模式和 Java基礎(chǔ)問題 String的+的性能及原理 java之yield(),sleep(),wait()區(qū)別詳解-備忘筆記 深入理解Java Stream流水...
閱讀 2794·2019-08-30 15:53
閱讀 2932·2019-08-29 16:20
閱讀 1135·2019-08-29 15:10
閱讀 1090·2019-08-26 10:58
閱讀 2252·2019-08-26 10:49
閱讀 694·2019-08-26 10:21
閱讀 769·2019-08-23 18:30
閱讀 1693·2019-08-23 15:58