Top Description Inners Fields Constructors Methods
java.util.concurrent.locks

public Class ReentrantReadWriteLock

extends Object
implements ReadWriteLock, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, java.util.concurrent.locks.ReadWriteLock
Imports
java.util.Collection, java.util.concurrent.TimeUnit, jdk.internal.vm.annotation.ReservedStackAccess

An implementation of ReadWriteLock supporting similar semantics to ReentrantLock.

This class has the following properties:

Serialization of this class behaves in the same way as built-in locks: a deserialized lock is in the unlocked state, regardless of its state when serialized.

Sample usages. Here is a code sketch showing how to perform lock downgrading after updating a cache (exception handling is particularly tricky when handling multiple locks in a non-nested fashion):

 class CachedData {
  Object data;
  boolean cacheValid;
  final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

  void processCachedData() {
    rwl.readLock().lock();
    // Code between the lock() above, and the unlock() below must not throw
    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
      }
    }
    // Make sure that code that could throw is executed inside the try block
    try {
      use(data);
    } finally {
      rwl.readLock().unlock();
    }
  }
}
ReentrantReadWriteLocks can be used to improve concurrency in some uses of some kinds of Collections. This is typically worthwhile only when the collections are expected to be large, accessed by more reader threads than writer threads, and entail operations with overhead that outweighs synchronization overhead. For example, here is a class using a TreeMap that is expected to be large and concurrently accessed.
 class RWDictionary {
  private final Map<String, Data> m = new TreeMap<>();
  private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
  private final Lock r = rwl.readLock();
  private final Lock w = rwl.writeLock();

  public Data get(String key) {
    r.lock();
    try { return m.get(key); }
    finally { r.unlock(); }
  }
  public List<String> allKeys() {
    r.lock();
    try { return new ArrayList<>(m.keySet()); }
    finally { r.unlock(); }
  }
  public Data put(String key, Data value) {
    w.lock();
    try { return m.put(key, value); }
    finally { w.unlock(); }
  }
  public void clear() {
    w.lock();
    try { m.clear(); }
    finally { w.unlock(); }
  }
}

Implementation Notes

This lock supports a maximum of 65535 recursive write locks and 65535 read locks. Attempts to exceed these limits result in Error throws from locking methods.

Author
Doug Lea
Since
1.5

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
ReentrantReadWriteLock.FairSync

Fair version of Sync

pack-priv static class
ReentrantReadWriteLock.NonfairSync

Nonfair version of Sync

public static class
pack-priv abstract static class
ReentrantReadWriteLock.Sync

Synchronization implementation for ReentrantReadWriteLock.

public static class

Field Summary

Modifier and TypeField and Description
private final ReentrantReadWriteLock.ReadLock
readerLock

Inner class providing readlock

private static final long
pack-priv final ReentrantReadWriteLock.Sync
sync

Performs all synchronization mechanics

private final ReentrantReadWriteLock.WriteLock
writerLock

Inner class providing writelock

Constructor Summary

AccessConstructor and Description
public
ReentrantReadWriteLock()

Creates a new ReentrantReadWriteLock with default (nonfair) ordering properties.

public
ReentrantReadWriteLock(boolean
true if this lock should use a fair ordering policy
fair
)

Creates a new ReentrantReadWriteLock with the given fairness policy.

Method Summary

Modifier and TypeMethod and Description
protected Thread

Returns:

the owner, or null if not owned
getOwner
()

Returns the thread that currently owns the write lock, or null if not owned.

protected Collection<Thread>

Returns:

the collection of threads
getQueuedReaderThreads
()

Returns a collection containing threads that may be waiting to acquire the read lock.

protected Collection<Thread>

Returns:

the collection of threads
getQueuedThreads
()

Returns a collection containing threads that may be waiting to acquire either the read or write lock.

protected Collection<Thread>

Returns:

the collection of threads
getQueuedWriterThreads
()

Returns a collection containing threads that may be waiting to acquire the write lock.

public final int

Returns:

the estimated number of threads waiting for this lock
getQueueLength
()

Returns an estimate of the number of threads waiting to acquire either the read or write lock.

public int

Returns:

the number of holds on the read lock by the current thread, or zero if the read lock is not held by the current thread
getReadHoldCount
()

Queries the number of reentrant read holds on this lock by the current thread.

public int

Returns:

the number of read locks held
getReadLockCount
()

Queries the number of read locks held for this lock.

protected Collection<Thread>

Returns:

the collection of threads
getWaitingThreads
(Condition
the condition
condition
)

Returns a collection containing those threads that may be waiting on the given condition associated with the write lock.

public int

Returns:

the estimated number of waiting threads
getWaitQueueLength
(Condition
the condition
condition
)

Returns an estimate of the number of threads waiting on the given condition associated with the write lock.

public int

Returns:

the number of holds on the write lock by the current thread, or zero if the write lock is not held by the current thread
getWriteHoldCount
()

Queries the number of reentrant write holds on this lock by the current thread.

public final boolean

Returns:

true if the given thread is queued waiting for this lock
hasQueuedThread
(Thread
the thread
thread
)

Queries whether the given thread is waiting to acquire either the read or write lock.

public final boolean

Returns:

true if there may be other threads waiting to acquire the lock
hasQueuedThreads
()

Queries whether any threads are waiting to acquire the read or write lock.

public boolean

Returns:

true if there are any waiting threads
hasWaiters
(Condition
the condition
condition
)

Queries whether any threads are waiting on the given condition associated with the write lock.

public final boolean

Returns:

true if this lock has fairness set true
isFair
()

Returns true if this lock has fairness set true.

public boolean

Returns:

true if any thread holds the write lock and false otherwise
isWriteLocked
()

Queries if the write lock is held by any thread.

public boolean

Returns:

true if the current thread holds the write lock and false otherwise
isWriteLockedByCurrentThread
()

Queries if the write lock is held by the current thread.

public ReentrantReadWriteLock.ReadLock
readLock()

Implements java.util.concurrent.locks.ReadWriteLock.readLock.

Returns the lock used for reading.

public String

Returns:

a string identifying this lock, as well as its lock state
toString
()

Overrides java.lang.Object.toString.

Returns a string identifying this lock, as well as its lock state.

public ReentrantReadWriteLock.WriteLock
writeLock()

Implements java.util.concurrent.locks.ReadWriteLock.writeLock.

Returns the lock used for writing.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAllwaitwaitwait