Readers writers problem concurrent Java

Ferguzz picture Ferguzz · May 22, 2011 · Viewed 7.6k times · Source

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

Answer

Jon Skeet picture Jon Skeet · May 22, 2011

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:

  • Don't extend Thread - you're not specializing the thread at all.
  • Don't use static variables like this from instance members; it makes it look like there's state on a per-object basis, but actually there isn't. Personally I'd just use instance variables.
  • Don't use underscores in names - the conventional Java names would be numReaders, readEnd (or better, endRead) etc.
  • Don't synchronize on either 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.
  • You never set 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.