The file Rw.java
contains a Java
program that implements this approach (using Java's variant of
condition variables). This
program provides a control panel with two buttons, one of which spawns
a Reader thread and the other of which spawns a Writer thread. The output
from the threads goes to the terminal window you ran Java from. Each
thread outputs a message upon creation, another upon acquiring the
access it needs, then sleeps for one to five seconds, and then outputs
another message indicating that it is done reading or writing and
releases the access right.
The only problem (as indicated by a comment in the code) is that the
acquireWriteAccess()
method has been designed in such a
way that a writer can wind up being delayed indefinitely by a steady
stream of overlapping readers, even though the writer can have arrived
on the scene before all but the first of the readers. (This is known
as ``starvation.'') Your assignment is to replace this method with one
that is starvation-free, so that the writer waits for any existing
readers to finish, but no new readers can start until after the writer
is done. This can be done without any changes outside that one
method, and with the new version of the method only being a few lines
of code longer than the old. Of course, your version must in addition
to being starvation free still ensure the basic readers/writers
condition, that if any thread has write access, there can be no other
thread with either read or write access.
There is no requirement that you actually try out the demo program before and after your modification (this is a homework, not a lab). However, I would encourage you to do so. You can quite easily and vividly see starvation happening in the unmodified program, as well as seeing the otherwise correct readers/writers behavior. You'll also be able to test the successfulness of your modification. See the lab 1 handout for more on compiling and running Java if you choose to try the program out. (Note that I didn't bother putting it into a package, so it doesn't need to be buried down a bunch of subdirectory levels like in the lab.) Ask if you need help with this.
Instructor: Max Hailperin