This is an implementation of readers writers, i.e. many readers can read but only one writer can write at any one time. Does this work as expected?
public class ReadersWriters extends Thread{
static int num_readers = 0;
static int writing = 0;
public void read_start() throws InterruptedException {
synchronized(this.getClass()) {
while(writing == 1) wait();
num_readers++;
}
}
public void read_end() {
synchronized(this.getClass()) {
if(--num_readers == 0) notifyAll();
}
}
public void write_start() throws InterruptedException{
synchronized(this.getClass()) {
while(num_readers > 0) wait();
writing = 1;
}
}
public void write_end() {
this.getClass().notifyAll();
}
}
Also is this implementation any different from declaring each method
public static synchronized read_start()
for example?
Thanks
No - you're implicitly calling this.wait()
, despite not having synchronized on this
, but instead on the class. Likewise you're calling this.notifyAll()
in read_end
. My suggestions:
Thread
- you're not specializing the thread at all.numReaders
, readEnd
(or better, endRead
) etc.this
or the class if you can help it. Personally I prefer to have a private final Object
variable to lock on (and wait etc). That way you know that only your code can be synchronizing on it, which makes it easier to reason about.writing
to 0. Any reason for using an integer instead of a boolean
in the first place?Of course, it's better to use the classes in the framework for this if at all possible - but I'm hoping you're really writing this to understand threading better.