//ReentrantReadWriteLock类中tryAcquireShared protectedfinalinttryAcquireShared(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; //写锁被占用,且不是由当前线程持有,返回-1
finalbooleanreaderShouldBlock(){ /* 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(); }
/** * Returns {@code true} if the apparent first queued thread, if one * exists, is waiting in exclusive mode. If this method returns * {@code true}, and the current thread is attempting to acquire in * shared mode (that is, this method is invoked from {@link * #tryAcquireShared}) then it is guaranteed that the current thread * is not the first queued thread. Used only as a heuristic in * ReentrantReadWriteLock. */ finalbooleanapparentlyFirstQueuedIsExclusive(){ Node h, s; return (h = head) != null && (s = h.next) != null && !s.isShared() && s.thread != null; }
protectedfinalbooleantryReleaseShared(int unused){ Thread current = Thread.currentThread(); if (firstReader == current) { // assert firstReaderHoldCount > 0; /** * 当前线程是第一个获取到锁的,如果此线程要释放锁了,则firstReader置空 * 否则,将线程持有的锁计数减1 */ if (firstReaderHoldCount == 1) firstReader = null; else firstReaderHoldCount--; } else { HoldCounter rh = cachedHoldCounter; //The hold count of the last thread to successfully acquire readLock if (rh == null || rh.tid != getThreadId(current)) rh = readHolds.get(); //readHolds表示当前线程所持有的可重入读锁数 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; } }
//ReentratReadWriteLock类中方法 protectedfinalbooleantryAcquire(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); //写锁被持有的次数,通过与低16位做与操作得到 if (c != 0) { //c!=0,说明存在锁,可能是读锁,也可能是写锁 // (Note: if c != 0 and w == 0 then shared count != 0) // c!=0,w==0,说明读锁存在 //w != 0 && current != getExclusiveOwnerThread() 表示其他线程获取了写锁。 if (w == 0 || current != getExclusiveOwnerThread()) //当w==0,表示读锁存在,则返回false,说明在线程正在读的时候,是不能进行写操作的 returnfalse; if (w + exclusiveCount(acquires) > MAX_COUNT) thrownew Error("Maximum lock count exceeded"); // Reentrant acquire //执行到这里,说明存在写锁,且由当前线程持有 // 重入计数 setState(c + acquires); returntrue; }
//执行到这里,说明不存在任何锁 if (writerShouldBlock() || !compareAndSetState(c, c + acquires)) returnfalse; setExclusiveOwnerThread(current); returntrue; }