java.util.concurrent.locks
Class ReentrantReadWriteLock

java.lang.Object
  extended byjava.util.concurrent.locks.ReentrantReadWriteLock
All Implemented Interfaces:
ReadWriteLock, java.io.Serializable

public class ReentrantReadWriteLock
extends java.lang.Object
implements ReadWriteLock, java.io.Serializable

An implementation of ReadWriteLock supporting similar semantics to ReentrantLock.

This class has the following properties:

Sample usage. Here is a code sketch showing how to exploit reentrancy to perform lock downgrading after updating a cache (exception handling is elided for simplicity):

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

   void processCachedData() {
     rwl.readLock().lock();
     if (!cacheValid) {
        // upgrade lock manually
        rwl.readLock().unlock();   // must unlock first to obtain writelock
        rwl.writeLock().lock();
        if (!cacheValid) { // recheck
          data = ...
          cacheValid = true;
        }
        // downgrade lock
        rwl.readLock().lock();  // reacquire read without giving up write lock
        rwl.writeLock().unlock(); // unlock write, still hold read
     }

     use(data);
     rwl.readLock().unlock();
   }
 }
 

Implementation Considerations

In addition to the above, this reference implementation has the following property:

Since:
1.5
Author:
Doug Lea
See Also:
Serialized Form

Constructor Summary
ReentrantReadWriteLock()
          Creates a new ReentrantReadWriteLock with default ordering properties.
ReentrantReadWriteLock(boolean fair)
          Creates a new ReentrantReadWriteLock with the given fairness policy.
 
Method Summary
 Lock readLock()
          Return the lock used for reading.
 Lock writeLock()
          Return the lock used for writing.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

ReentrantReadWriteLock

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


ReentrantReadWriteLock

public ReentrantReadWriteLock(boolean fair)
Creates a new ReentrantReadWriteLock with the given fairness policy.

Parameters:
fair - true if this lock should use a fair ordering policy
Method Detail

writeLock

public Lock writeLock()
Description copied from interface: ReadWriteLock
Return the lock used for writing.

Specified by:
writeLock in interface ReadWriteLock

readLock

public Lock readLock()
Description copied from interface: ReadWriteLock
Return the lock used for reading.

Specified by:
readLock in interface ReadWriteLock