在上一篇 Java併發核心淺談 咱們大概瞭解到了Lock
和synchronized
的共同點,再簡單總結下:java
Lock
主要是自定義一個 counter,從而利用CAS
對其實現原子操做,而synchronized
是c++ hotspot
實現的 monitor(具體的咱也沒看,咱就不說)舉個例子:線程 A 持有了某個對象的 monitor,其它線程在訪問該對象時,發現 monitor 不爲 0,因此只能阻塞掛起或者加入等待隊列,等着線程 A 處理完退出後將 monitor 置爲 0。在線程 A 處理任務期間,其它線程要麼循環訪問 monitor,要麼一直阻塞等着線程 A 喚醒,再不濟就真的如我所說,放棄鎖的競爭,去處理別的任務。可是應該作不到去處理別的任務後,任務處理到一半,被線程 A 通知後再回去搶鎖node
不共享 counterc++
// 非公平鎖在第一次拿鎖失敗也會調用該方法 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;
讀鎖:共享 countersegmentfault
寫鎖:不共享 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
鏈表併發
讀寫鎖,能夠粗略的理解爲讀和寫兩種狀態,因此這兒的設計相似線程池的狀態。只不過,讀計數是能夠多個讀線程共享的(排除寫鎖),每一個讀的線程都會維護本身的讀計數。寫鎖的話,獨佔寫計數,排除一切其餘線程。app