Home > Net >  What if notifyAll is called at the start of critical section
What if notifyAll is called at the start of critical section

Time:03-20

What if notifyAll is called at the start of critical section where lock is not released and released at the end of cs(critical section). What will happen to waiting threads?

Do the notifyAll will get heard by all threads and all thread will try to get lock and get unsuccessful(since notify/notifyAll do not release lock) and keep on trying until they get the lock?

So, what difference it makes to call notify at the start of critical section or at the end ?why it is recommended to call notifyAll at the end of cs?

CodePudding user response:

When you call notifyAll() all waiting threads are reactivated and try to acquire the lock on the object on which you called notifyAll().

IMHO the correctness of your code is not sacrificed - no other thread can acquire the lock as long as it is held by the current thread (the one calling notifyAll()).

But the performance will suffer - waking up threads takes processor resources, having them try to acquire the lock takes processor resources, waiting for the release of the lock takes processor resources.


Often the advice to call notifyAll() at the end of a critical section is fulfilled trivially because your thread is doing some processing in a critical section and at the end of that processing it notices that it should notify waiting threads that they can continue. In that case notifying other threads that they can continue before being sure that this is really the case doesn't make any sense.

  • Related