摘要:在線程處理任務期間,其它線程要么循環訪問,要么一直阻塞等著線程喚醒,再不濟就真的如我所說,放棄鎖的競爭,去處理別的任務。寫鎖的話,獨占寫計數,排除一切其他線程。
回顧
在上一篇 Java并發核心淺談 我們大概了解到了Lock和synchronized的共同點,再簡單總結下:
Lock主要是自定義一個 counter,從而利用CAS對其實現原子操作,而synchronized是c++ hotspot實現的 monitor(具體的咱也沒看,咱就不說)
二者都可重入(遞歸,互調,循環),其本質都是維護一個可計數的 counter,在其它線程訪問加鎖對象時會判斷 counter 是否為 0
理論上講二者都是阻塞式的,因為線程在拿鎖時,如果拿不到,最終的結果只能等待(前提是線程的最終目的就是要獲取鎖)讀寫鎖分離成兩把鎖了,所以不一樣
舉個例子:線程 A 持有了某個對象的 monitor,其它線程在訪問該對象時,發現 monitor 不為 0,所以只能阻塞掛起或者加入等待隊列,等著線程 A 處理完退出后將 monitor 置為 0。在線程 A 處理任務期間,其它線程要么循環訪問 monitor,要么一直阻塞等著線程 A 喚醒,再不濟就真的如我所說,放棄鎖的競爭,去處理別的任務。但是應該做不到去處理別的任務后,任務處理到一半,被線程 A 通知后再回去搶鎖
公平鎖與非公平鎖不共享 counter
// 非公平鎖在第一次拿鎖失敗也會調用該方法 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 計數 protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); // 拿到計數 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; // 當前線程處于頭節點的下一個且不為空則不用排隊 // 或該線程就是當前持有鎖的線程,即重入鎖,也不用排隊 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; } // 獲取失敗會檢查節點狀態 // 然后 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 位為讀計數,低 16 位為寫計數 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; } /** * A counter for per-thread read hold counts. 每個線程自己的讀計數 * 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(); // 如果寫鎖計數不為零,且當前線程不是寫鎖持有線程,則可以獲得讀鎖 // 言外之意,獲得寫鎖的線程不可以再獲得讀鎖 // 個人認為不用判斷寫計數也行 if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; // 獲得讀計數 int r = sharedCount(c); // 檢查等待隊列 讀計數上限 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 每個線程自己的讀計數,非共享。但是鎖計數與其它讀操作共享,不與寫操作共享 // 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.) // 計數器已達最大值,獲得鎖失敗 * 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; } // 隊列策略 // state 為 0,檢查是否需要排隊 // 針對公平鎖:去排隊,如果當前線程在隊首或等待隊列為空,則返回 false,自然會走后面的 CAS // 否則就返回 true,則進入 return false; // 針對非公平鎖:寫死為 false,直接 CAS if (writerShouldBlock() || !compareAndSetState(c, c + acquires)) return false; // 設置當前寫鎖持有線程 setExclusiveOwnerThread(current); return true; } // 因為讀鎖是多個線程共享讀計數,各自維護了自己的讀計數,所以釋放的時候比寫鎖釋放要多些操作 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; } }總結一下
公平鎖和非公平鎖的“鎖”實現是基于CAS,公平性基于內部維護的Node鏈表
讀寫鎖,可以粗略的理解為讀和寫兩種狀態,所以這兒的設計類似線程池的狀態。只不過,讀計數是可以多個讀線程共享的(排除寫鎖),每個讀的線程都會維護自己的讀計數。寫鎖的話,獨占寫計數,排除一切其他線程。
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/77772.html
摘要:耐心看完的你或多或少會有收獲并發的核心就是包,而的核心是抽象隊列同步器,簡稱,一些鎖啊信號量啊循環屏障啊都是基于。 耐心看完的你或多或少會有收獲! Java并發的核心就是 java.util.concurrent 包,而 j.u.c 的核心是AbstractQueuedSynchronizer抽象隊列同步器,簡稱 AQS,一些鎖啊!信號量啊!循環屏障啊!都是基于AQS。而 AQS 又是...
摘要:物理計算機并發問題在介紹內存模型之前,先簡單了解下物理計算機中的并發問題。基于高速緩存的存儲交互引入一個新的問題緩存一致性。寫入作用于主內存變量,把操作從工作內存中得到的變量值放入主內存的變量中。 物理計算機并發問題 在介紹Java內存模型之前,先簡單了解下物理計算機中的并發問題。由于處理器的與存儲設置的運算速度有幾個數量級的差距,所以現代計算機加入一層讀寫速度盡可能接近處理器的高速緩...
摘要:比如需要用多線程或分布式集群統計一堆用戶的相關統計值,由于用戶的統計值是共享數據,因此需要保證線程安全。如果類是無狀態的,那它永遠是線程安全的。參考探索并發編程二寫線程安全的代碼 線程安全類 保證類線程安全的措施: 不共享線程間的變量; 設置屬性變量為不可變變量; 每個共享的可變變量都使用一個確定的鎖保護; 保證線程安全的思路: 1. 通過架構設計 通過上層的架構設計和業務分析來避...
摘要:線程池的作用降低資源消耗。通過重復利用已創建的線程降低線程創建和銷毀造成的資源浪費。而高位的部分,位表示線程池的狀態。當線程池中的線程數達到后,就會把到達的任務放到中去線程池的最大長度。默認情況下,只有當線程池中的線程數大于時,才起作用。 線程池的作用 降低資源消耗。通過重復利用已創建的線程降低線程創建和銷毀造成的資源浪費。 提高響應速度。當任務到達時,不需要等到線程創建就能立即執行...
摘要:基礎問題的的性能及原理之區別詳解備忘筆記深入理解流水線抽象關鍵字修飾符知識點總結必看篇中的關鍵字解析回調機制解讀抽象類與三大特征時間和時間戳的相互轉換為什么要使用內部類對象鎖和類鎖的區別,,優缺點及比較提高篇八詳解內部類單例模式和 Java基礎問題 String的+的性能及原理 java之yield(),sleep(),wait()區別詳解-備忘筆記 深入理解Java Stream流水...
閱讀 2631·2019-08-30 15:53
閱讀 2870·2019-08-29 16:20
閱讀 1081·2019-08-29 15:10
閱讀 1018·2019-08-26 10:58
閱讀 2188·2019-08-26 10:49
閱讀 630·2019-08-26 10:21
閱讀 700·2019-08-23 18:30
閱讀 1635·2019-08-23 15:58