Assume I have a Read/Write monitor implementation in Java.
Several Readers OR One Writer can access the database at any one time (not both)
class RWmonitor{
private int readers = 0;
private boolean writing = false;
public synchronized void StartRead(){ ..}
public synchronized void EndRead(){
notifyAll();
readers--;
}
public synchronized void StartWrite(){ ..}
public synchronized void EndWrite(){
notifyAll();
writing = false;
}
}
Now, does it matter if notifyAll()
is not the last statement in the synchronized method?
Assume:
1) EndRead()
executes
2) notifyAll()
notifies all waiting threads
3) Then it reduces the reader count.
When it executes notifyAll()
, will it just be more costly since the woken up threads would be waiting for the lock on RWmonitor to be released? (assuming the thread that has the lock on RWmonitor is still at readers--;
)
It does not matter if it is the last statement.
To quote the javadoc for notifyAll():