classCachedData{ Object data; volatileboolean cacheValid; final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
voidprocessCachedData(){ rwl.readLock().lock(); if (!cacheValid) { // Must release read lock before acquiring write lock rwl.readLock().unlock(); rwl.writeLock().lock(); try { // Recheck state because another thread might have // acquired write lock and changed state before we did. if (!cacheValid) { data = ... cacheValid = true; } // Downgrade by acquiring read lock before releasing write lock rwl.readLock().lock(); } finally { rwl.writeLock().unlock(); // Unlock write, still hold read } }
classRWDictionary{ privatefinal Map<String, Data> m = new TreeMap<String, Data>(); privatefinal ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); privatefinal Lock r = rwl.readLock(); privatefinal Lock w = rwl.writeLock();
public Data get(String key){ r.lock(); try { return m.get(key); } finally { r.unlock(); } }
/** Inner class providing readlock */ privatefinal ReentrantReadWriteLock.ReadLock readerLock; /** Inner class providing writelock */ privatefinal ReentrantReadWriteLock.WriteLock writerLock; /** Performs all synchronization mechanics */ final Sync sync;
/** * Creates a new {@code ReentrantReadWriteLock} with * default (nonfair) ordering properties. */ publicReentrantReadWriteLock(){ this(false); }
/** * Creates a new {@code ReentrantReadWriteLock} with * the given fairness policy. * * @param fair {@code true} if this lock should use a fair ordering policy */ publicReentrantReadWriteLock(boolean fair){ sync = fair ? new FairSync() : new NonfairSync(); readerLock = new ReadLock(this); writerLock = new WriteLock(this); }
public ReentrantReadWriteLock.WriteLock writeLock(){ return writerLock; } public ReentrantReadWriteLock.ReadLock readLock(){ return readerLock; }
/** * Synchronization implementation for ReentrantReadWriteLock. * Subclassed into fair and nonfair versions. */ abstractstaticclassSyncextendsAbstractQueuedSynchronizer{ privatestaticfinallong serialVersionUID = 6317671515068378041L;
/* * Read vs write count extraction constants and functions. * Lock state is logically divided into two unsigned shorts: * The lower one representing the exclusive (writer) lock hold count, * and the upper the shared (reader) hold count. */
/** Returns the number of shared holds represented in count */ staticintsharedCount(int c){ return c >>> SHARED_SHIFT; } /** Returns the number of exclusive holds represented in count */ staticintexclusiveCount(int c){ return c & EXCLUSIVE_MASK; }
/** * A counter for per-thread read hold counts. * Maintained as a ThreadLocal; cached in cachedHoldCounter */ staticfinalclassHoldCounter{ int count = 0; // Use id, not reference, to avoid garbage retention finallong tid = getThreadId(Thread.currentThread()); }
/** * ThreadLocal subclass. Easiest to explicitly define for sake * of deserialization mechanics. */ staticfinalclassThreadLocalHoldCounter extendsThreadLocal<HoldCounter> { public HoldCounter initialValue(){ returnnew HoldCounter(); } }
/** * The number of reentrant read locks held by current thread. * Initialized only in constructor and readObject. * Removed whenever a thread's read hold count drops to 0. */ privatetransient ThreadLocalHoldCounter readHolds;
/** * The hold count of the last thread to successfully acquire * readLock. This saves ThreadLocal lookup in the common case * where the next thread to release is the last one to * acquire. This is non-volatile since it is just used * as a heuristic, and would be great for threads to cache. * * <p>Can outlive the Thread for which it is caching the read * hold count, but avoids garbage retention by not retaining a * reference to the Thread. * * <p>Accessed via a benign data race; relies on the memory * model's final field and out-of-thin-air guarantees. */ privatetransient HoldCounter cachedHoldCounter;
/** * firstReader is the first thread to have acquired the read lock. * firstReaderHoldCount is firstReader's hold count. * * <p>More precisely, firstReader is the unique thread that last * changed the shared count from 0 to 1, and has not released the * read lock since then; null if there is no such thread. * * <p>Cannot cause garbage retention unless the thread terminated * without relinquishing its read locks, since tryReleaseShared * sets it to null. * * <p>Accessed via a benign data race; relies on the memory * model's out-of-thin-air guarantees for references. * * <p>This allows tracking of read holds for uncontended read * locks to be very cheap. */ privatetransient Thread firstReader = null; privatetransientint firstReaderHoldCount;
Sync() { readHolds = new ThreadLocalHoldCounter(); setState(getState()); // ensures visibility of readHolds }
/* * Acquires and releases use the same code for fair and * nonfair locks, but differ in whether/how they allow barging * when queues are non-empty. */
/** * Returns true if the current thread, when trying to acquire * the read lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. */ abstractbooleanreaderShouldBlock();
/** * Returns true if the current thread, when trying to acquire * the write lock, and otherwise eligible to do so, should block * because of policy for overtaking other waiting threads. */ abstractbooleanwriterShouldBlock();
/* * Note that tryRelease and tryAcquire can be called by * Conditions. So it is possible that their arguments contain * both read and write holds that are all released during a * condition wait and re-established in tryAcquire. */
protectedfinalbooleantryRelease(int releases){ if (!isHeldExclusively()) thrownew IllegalMonitorStateException(); int nextc = getState() - releases; boolean free = exclusiveCount(nextc) == 0; if (free) setExclusiveOwnerThread(null); setState(nextc); return free; }
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); if (c != 0) { // (Note: if c != 0 and w == 0 then shared count != 0) if (w == 0 || current != getExclusiveOwnerThread()) 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; }
protectedfinalbooleantryReleaseShared(int unused){ Thread current = Thread.currentThread(); if (firstReader == current) { // assert firstReaderHoldCount > 0; if (firstReaderHoldCount == 1) firstReader = null; else firstReaderHoldCount--; } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != 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; } }
private IllegalMonitorStateException unmatchedUnlockException(){ returnnew IllegalMonitorStateException( "attempt to unlock read lock, not locked by current thread"); }
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; int r = sharedCount(c); if (!readerShouldBlock() && r < MAX_COUNT && compareAndSetState(c, c + SHARED_UNIT)) { if (r == 0) { firstReader = current; firstReaderHoldCount = 1; } elseif (firstReader == current) { firstReaderHoldCount++; } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) cachedHoldCounter = rh = readHolds.get(); elseif (rh.count == 0) readHolds.set(rh); rh.count++; } return1; } return fullTryAcquireShared(current); }
/** * Full version of acquire for reads, that handles CAS misses * and reentrant reads not dealt with in tryAcquireShared. */ finalintfullTryAcquireShared(Thread current){ /* * 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. */ HoldCounter rh = null; for (;;) { int c = getState(); if (exclusiveCount(c) != 0) { if (getExclusiveOwnerThread() != current) return -1; // else we hold the exclusive lock; blocking here // would cause deadlock. } elseif (readerShouldBlock()) { // Make sure we're not acquiring read lock reentrantly if (firstReader == current) { // assert firstReaderHoldCount > 0; } else { if (rh == null) { rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) { rh = readHolds.get(); if (rh.count == 0) readHolds.remove(); } } if (rh.count == 0) return -1; } } if (sharedCount(c) == MAX_COUNT) thrownew Error("Maximum lock count exceeded"); if (compareAndSetState(c, c + SHARED_UNIT)) { if (sharedCount(c) == 0) { firstReader = current; firstReaderHoldCount = 1; } elseif (firstReader == current) { firstReaderHoldCount++; } else { if (rh == null) rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) rh = readHolds.get(); elseif (rh.count == 0) readHolds.set(rh); rh.count++; cachedHoldCounter = rh; // cache for release } return1; } } }
/** * Performs tryLock for write, enabling barging in both modes. * This is identical in effect to tryAcquire except for lack * of calls to writerShouldBlock. */ finalbooleantryWriteLock(){ Thread current = Thread.currentThread(); int c = getState(); if (c != 0) { int w = exclusiveCount(c); if (w == 0 || current != getExclusiveOwnerThread()) returnfalse; if (w == MAX_COUNT) thrownew Error("Maximum lock count exceeded"); } if (!compareAndSetState(c, c + 1)) returnfalse; setExclusiveOwnerThread(current); returntrue; }
/** * Performs tryLock for read, enabling barging in both modes. * This is identical in effect to tryAcquireShared except for * lack of calls to readerShouldBlock. */ finalbooleantryReadLock(){ Thread current = Thread.currentThread(); for (;;) { int c = getState(); if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) returnfalse; int r = sharedCount(c); if (r == MAX_COUNT) thrownew Error("Maximum lock count exceeded"); if (compareAndSetState(c, c + SHARED_UNIT)) { if (r == 0) { firstReader = current; firstReaderHoldCount = 1; } elseif (firstReader == current) { firstReaderHoldCount++; } else { HoldCounter rh = cachedHoldCounter; if (rh == null || rh.tid != getThreadId(current)) cachedHoldCounter = rh = readHolds.get(); elseif (rh.count == 0) readHolds.set(rh); rh.count++; } returntrue; } } }
protectedfinalbooleanisHeldExclusively(){ // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); }
// Methods relayed to outer class
final ConditionObject newCondition(){ returnnew ConditionObject(); }
final Thread getOwner(){ // Must read state before owner to ensure memory consistency return ((exclusiveCount(getState()) == 0) ? null : getExclusiveOwnerThread()); }
int count = readHolds.get().count; if (count == 0) readHolds.remove(); return count; }
/** * Reconstitutes the instance from a stream (that is, deserializes it). */ privatevoidreadObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); readHolds = new ThreadLocalHoldCounter(); setState(0); // reset to unlocked state }
/** * The lock returned by method {@link ReentrantReadWriteLock#readLock}. */ publicstaticclassReadLockimplementsLock, java.io.Serializable{ privatestaticfinallong serialVersionUID = -5992448646407690164L; privatefinal Sync sync;
/** * Constructor for use by subclasses * * @param lock the outer lock object * @throws NullPointerException if the lock is null */ protectedReadLock(ReentrantReadWriteLock lock){ sync = lock.sync; }
/** *如果在给定的等待时间内另一个线程未持有写锁定并且当前线程未被中断,则获取读锁定 * * 如果写锁未被另一个线程持有,则获取读锁,并立即返回true值。 * 如果已将此锁设置为使用公平的排序策略,则在任何其他线程正在等待该锁的情况下, * 将不会获取可用锁。 这与tryLock()方法相反。 * 如果您想要定时的tryLock确实允许对公平锁进行插入,则将定时和非定时形式组合在一起: * if (lock.tryLock() || * lock.tryLock(timeout, unit)) { * ... * } * * 如果写锁由另一个线程持有,则出于线程调度目的,当前线程将被禁用 * ,并且在发生以下三种情况之一之前,它处于休眠状态: * 1 读锁由当前线程获取; * 2 其他一些线程中断当前线程 * 3 经过指定的等待时间 * 如果获取了读锁,则返回值true。 * *如果当前线程: * 1 在进入此方法时设置了其中断状态 * 2 获取读取锁时中断 * 然后抛出InterruptedException并清除当前线程的中断状态。 * * 如果经过了指定的等待时间,则返回值false。 如果时间小于或等于零,则该方法将完全不等待 * * 在此实现中,由于此方法是显式的中断点,因此优先于对中断的响应, * 而不是正常或可重入的锁定获取,而是优先报告等待时间的流逝 * * @param timeout the time to wait for the read lock * @param unit the time unit of the timeout argument * @return {@code true} if the read lock was acquired * @throws InterruptedException if the current thread is interrupted * @throws NullPointerException if the time unit is null */ publicbooleantryLock(long timeout, TimeUnit unit) throws InterruptedException { return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); }
/** * 尝试释放此锁。 * * <p>If the number of readers is now zero then the lock * is made available for write lock attempts. */ publicvoidunlock(){ sync.releaseShared(1); }
/** * Throws {@code UnsupportedOperationException} because * {@code ReadLocks} do not support conditions. * * @throws UnsupportedOperationException always */ public Condition newCondition(){ thrownew UnsupportedOperationException(); }
/** * 返回标识此锁定及其锁定状态的字符串。 括号中的状态包括字符串“ Read locks =”,后跟持有的读锁的数量。 * * @return a string identifying this lock, as well as its lock state */ public String toString(){ int r = sync.getReadLockCount(); returnsuper.toString() + "[Read locks = " + r + "]"; } }
/** * The lock returned by method {@link ReentrantReadWriteLock#writeLock}. */ publicstaticclassWriteLockimplementsLock, java.io.Serializable{ privatestaticfinallong serialVersionUID = -4992448646407690164L; privatefinal Sync sync;
/** * Constructor for use by subclasses * * @param lock the outer lock object * @throws NullPointerException if the lock is null */ protectedWriteLock(ReentrantReadWriteLock lock){ sync = lock.sync; }
/** * 如果当前线程是此锁的持有者,则保留计数将减少。 * 如果保持计数现在为零,则释放锁定。 * 如果当前线程不是此锁的持有者,则抛出IllegalMonitorStateException。 * * @throws IllegalMonitorStateException if the current thread does not * hold this lock */ publicvoidunlock(){ sync.release(1); }
/** * Returns a string identifying this lock, as well as its lock * state. The state, in brackets includes either the String * {@code "Unlocked"} or the String {@code "Locked by"} * followed by the {@linkplain Thread#getName name} of the owning thread. * * @return a string identifying this lock, as well as its lock state */ public String toString(){ Thread o = sync.getOwner(); returnsuper.toString() + ((o == null) ? "[Unlocked]" : "[Locked by thread " + o.getName() + "]"); }
/** * Queries if this write lock is held by the current thread. * Identical in effect to {@link * ReentrantReadWriteLock#isWriteLockedByCurrentThread}. * * @return {@code true} if the current thread holds this lock and * {@code false} otherwise * @since 1.6 */ publicbooleanisHeldByCurrentThread(){ return sync.isHeldExclusively(); }
/** * Queries the number of holds on this write lock by the current * thread. A thread has a hold on a lock for each lock action * that is not matched by an unlock action. Identical in effect * to {@link ReentrantReadWriteLock#getWriteHoldCount}. * * @return the number of holds on this lock by the current thread, * or zero if this lock is not held by the current thread * @since 1.6 */ publicintgetHoldCount(){ return sync.getWriteHoldCount(); } }