img
. . .
In the UNIX98 implementation of RWlocks, blocked threads are placed on the writer's sleep
queue in priority order. (Priorities are uninteresting for readers.) We ignore priorities in our
implementation, which is the right thing to do for most cases--better a faster, slightly unfair
RWlock than a slower, fairer one.
You will be disappointed to discover that none of the three libraries define RWlocks. However, all
is not lost. They can be built out of the primitives already available to you--mutexes and
condition variables. We build them in our extensions library. RWlocks are also defined in
UNIX98. A good example of using RWlocks is in Global RWLock with Global Mutex to Protect
Salaries.
In our sample Java implementation (shown in Code Example 7-1), we use the explicit condition
variables and mutexes. This allows us to send wakeups to only that set of waiters (either one
writer or all readers) when we need to. If we had used native Java wait/ notify, we would have had
to wake up all sleepers at every wakeup point. In the vast majority of cases, that would not be a
problem, as we've already assumed that writers are rare.
Example 7-1 Readers/Writer Locks in Java
//
Extensions/RWLock.java
package Extensions;
import java.io.*;
public class RWLock {
Thread
owner = null;
int
nCurrentReaders = 0;
int
nWaitingWriters = 0;
int
nWaitingReaders = 0;
Mutex
m =  new Mutex();
ConditionVar readersCV = new  ConditionVar();
ConditionVar writersCV = new  ConditionVar();
public String toString() {
String name;
if (owner == null)
name = "null";
else
name = owner.getName();
return "<RWLock: o:" + name + " r:" + nCurrentReaders + "
ww:"
+ nWaitingWriters + " wr:" + nWaitingReaders + m +">";
}
public void readLock() {
m.lock();
nWaitingReaders++;
while ((owner != null) || (nWaitingWriters > 0)) {
readersCV.condWait(m);
}
nWaitingReaders--;
nCurrentReaders++;
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home