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


Animation of Writers-Preferred Monitor


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



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


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


TestWritersPreferred The Writers-Preferred Monitor

The Writers-Preferred Monitor will give the resource to a writer, if any is waiting. Only if there is no writer available will it be given to readers.

If you run this animation with threads choosing randomly whether to read or write, you will observe that more and more threads accumulate waiting to write until there are no writers left. Then all the waiting readers will run.

If you run it with a fixed set of readers, a batch of readers may run before the first writer enters the monitor, but thereafter, typically, all the writers will run to completion before any readers run again. (You can set the number of readers and rest time to give the readers a better chance.)

State of the monitor

The state of the 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


If a thread tries to start reading, it must wait until there are no threads either writing or waiting to write; which is to say, it must wait until nwtotal is zero.

public synchronized void startReading()
        throws InterruptedException{
    while (nwtotal!=0) wait();


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

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


When the last reader of a group finishes reading, it wakes up all waiting readers and writers. If there are any waiting writers, no reader will be able to start reading, but will wait again. Eventually a writer will sieze the monitor and start writing.

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


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--;