Methods Summary |
---|
public synchronized void | acquireReadLock()This method is used to acquire a read lock. If there is already a writer thread
accessing the object using the RWLock then the reader thread will wait until
the writer completes its operation
if (currentWriters == 0 && writerQueue.size() == 0) {
++currentReaders;
} else {
++pendingReaders;
try {
wait();
} catch(InterruptedException ie) {
_logger.log(Level.FINE,"Error in acquireReadLock",ie);
}
}
|
public void | acquireWriteLock()This method is used to acquire a write lock. If there are already reader threads
accessing the object using the RWLock, then the writer thread will wait till all
the reader threads are finished with their operations.
Object lock = new Object();
synchronized(lock) {
synchronized(this) {
if (writerQueue.size() == 0 && currentReaders == 0 && currentWriters == 0) {
++currentWriters;
// Use logging facility if you need to log this
//_logger.log(Level.FINE," RW: incremented WriterLock count");
return;
}
writerQueue.enQueue(lock);
// Use logging facility if you need to log this
//_logger.log(Level.FINE," RW: Added WriterLock to queue");
}
try {
lock.wait();
} catch(InterruptedException ie) {
_logger.log(Level.FINE,"Error in acquireWriteLock",ie);
}
}
|
public boolean | isWriteLocked()isWriteLocked
returns true if the RWLock is in a write locked state.
return currentWriters > 0 ;
|
private void | notifyReaders()
currentReaders += pendingReaders;
pendingReaders = 0;
notifyAll();
|
private void | notifyWriters()
if (writerQueue.size() > 0) {
Object lock = writerQueue.deQueueFirst();
++currentWriters;
synchronized(lock) {
lock.notify();
}
}
|
public synchronized void | releaseReadLock()This method is used to release a read lock.
It also notifies any waiting writer thread
that it could now acquire a write lock.
if (--currentReaders == 0)
notifyWriters();
|
public synchronized void | releaseWriteLock()This method is used to release a write lock. It also notifies any pending
readers that they could now acquire the read lock. If there are no reader
threads then it will try to notify any waiting writer thread that it could now
acquire a write lock.
--currentWriters;
if (pendingReaders > 0)
notifyReaders();
else
notifyWriters();
|