Java Reference
In-Depth Information
locked. The readers share the bathroom, passing through concurrently. Writ-
ers use the bathroom exclusively. We should not force people simply passing
through to wait, but that's precisely what our sample application does. We
allow only one user of the bathroom, analogous to our cache objects, to pass
through at any given time, regardless of the use. I'm reasonably certain that I
have seen bathroom lines at many parties that indicated use of this algorithm.
If the read / write ratio is very high, then the penalty can be significant.
Read/write locks allow correct shared access
Database systems solve this problem with a multilevel locking system. In this
case, obtaining a read lock on a database object allows multiple users to read
the same data. A write lock is not compatible with a read lock. An application
requesting a write lock must wait for all readers to clear. Java has no native
support for read / write locks, but creating an object to provide this functional-
ity is straightforward. To see how a read / write lock works, we present an
example provided by Amandeep Singh, from a self-published article titled
“Implementing Read-Write Locks in Java”:
class RWLock
private int givenLocks;
private int waitingWriters;
private int waitingReaders;
private Object mutex;
public void getReadLock()
while((givenLocks == -1) ||
(waitingWriters != 0))
This method is used to request the read lock. It locks our common object,
mutex , to control access to the internal variables. If writers are waiting or if
writers have a lock, they're allowed to clear before the lock is granted. given-
Locks has a value of -1 when a writer has the lock:
Search WWH ::

Custom Search