Class ReaderWriterLock


  • public class ReaderWriterLock
    extends Object
    This reader/writer lock prevents reads from occurring while writes are in progress, and it also prevents multiple writes from happening simultaneously. Multiple read operations can run in parallel, however. Reads take priority over writes, so any read operations that are pending while a write is in progress will execute before any subsequent writes execute. Writes are guaranteed to execute in the order in which they were requested -- the oldest request is processed first. You should use the lock as follows: public class Data_structure_or_resource { ReaderWriterLock lock = new ReaderWriterLock(); public void access() { try{ lock.readRequest(); // do the read/access operation here. }finally { lock.readDone(); } } public void modify( ) { try { lock.writeRequest(); // do the write/modify operation here. } finally { lock.writeDone(); } }
    • Constructor Detail

      • ReaderWriterLock

        public ReaderWriterLock()
    • Method Detail

      • readRequest

        public void readRequest()
        Request the read lock. Block until a read operation can be performed safely. This call must be followed by a call to readDone() when the read operation completes.
      • readRequestImmediate

        public boolean readRequestImmediate()
        This version of read() requests read access and returns true if you get it. If it returns false, you may not safely read from the guarded resource. If it returns true, you should do the read, then call readDone in the normal way. Here's an example: public void read() { if( lock.readRequestImmediate() ) { try { // do the read operation here } finally { lock.readDone(); } }else { // couldn't read safely. }
      • readDone

        public void readDone()
        Release the lock. You must call this method when you're done with the read operation.
      • writeRequest

        public void writeRequest()
        Request the write lock. Block until a write operation can be performed safely. Write requests are guaranteed to be executed in the order received. Pending read requests take precedence over all write requests. This call must be followed by a call to writeDone() when the write operation completes.
      • writeRequestImmediate

        public boolean writeRequestImmediate()
        This version of the write request returns false immediately (without blocking) if any read or write operations are in progress and a write isn't safe; otherwise, it returns true and acquires the resource. Use it like this: public void write() { if( lock.writeRequestImmediate() ) { try { // do the write operation here } finally { lock.writeDone(); } }else { // couldn't write safely. } }
      • writeDone

        public void writeDone()
        Release the lock. You must call this method when you're done with the read operation.