javaconcurrencyreaderwriterlock

Readers writers problem concurrent Java


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


Solution

  • 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:

    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.