ali
ali

Reputation: 881

notifyall() not the last statement

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

Upvotes: 0

Views: 268

Answers (2)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

No, it doesn't matter. The lock will still be held until the end of the synchronized block, and no threads will be able to wait on the lock in the intervening time. In fact it is slightly advantageous to have the notify first in that an exception may stop the update but not the notify.

Upvotes: 3

Keppil
Keppil

Reputation: 46239

It does not matter if it is the last statement.

To quote the javadoc for notifyAll():

The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object.

Upvotes: 4

Related Questions