Thomas W. Christopher Consulting in High Performance Computing.
Training in Concurrency, Networking, and Parallelism, especially in Python and Java.

 

Animation of Readers-Preferred Monitor

Abstract

This page animates the Readers-Preferred policy for coordinating multiple readers and writers of a shared resource.

 

Author

Thomas W. Christopher
Tools of Computing
tc AT tools HYPHEN of HYPHEN computing DOT com

Requirements

This requires Java JDK1.1 or greater. It uses the 1.1 event model that is not implemented in earlier versions of Java.

 

TestReadersPreferred The Readers-Preferred Monitor

The Readers-Preferred Monitor will give the resource to a reader, if there is any available. Only if there are no reader present will the resource be given to a writer.

If you run this animation with threads choosing randomly whether to read or write, you will notice that most threads end up waiting to write for a long time.

If you run it with a fixed number of readers, you will observe the animation alternately giving the resource to a batch of readers and then to a writer while the readers are resting.


State of the monitor

As with the Writers-Preferred Monitor, the state of this monitor is contained in four variables:

nr: the number of threads currently reading, >=0
nw: the number of threads currently writing, 0 or 1
nrtotal: the number of threads either reading or waiting to read. nrtotal>=nr.
nwtotal: the number of threads either writing or waiting to write.

Behavior of the monitor

startReading

If a thread tries to start reading, it must wait until there are no threads currently writing; which is to say, it must wait until nw is zero.

 public synchronized void startReading() 
		throws InterruptedException{
	nrtotal++;
	while (nw!=0) wait();
	nr++;
 }
      

startWriting

To start writing, a thread must wait until there are no other threads reading or waiting to read or writing, indicated by nrtotal and nw both equaling zero.

 public synchronized void startWriting() 
		throws InterruptedException{
	nwtotal++;
	while (nrtotal+nw != 0) wait();
	nw=1;
 }
      

stopReading

When the last reader present finishes reading, it wakes up a waiting writer (if there are any present), which will sieze the monitor and start writing.

 public synchronized void stopReading(){
	nr--; nrtotal--;
	if (nrtotal==0) notify();
 }
      

stopWriting

When a writer finishes writing, it wakes up all waiting readers and writers to let them compete for the monitor.

 public synchronized void stopWriting(){
	nw=0; nwtotal--;
	notifyAll();
 }