educative.io

Notify vs NotifyAll

Hi,

There’s an explanation as to why we should use notifyAll rather than notify for the producer-consumer problem which seems correct. Though while implementing the Counting semaphore, wouldn’t we run into the same issue, then why are we using notify here instead of notifyAll?

Thanks,

2 Likes

The given solution will work for single producer and single consumer, The same will not work if there are multiple producers and consumers in case of CountingSemaphore I think.

The problem of deadlock applies here only if the counting semaphore is size 1.
If it is size 1, then the semaphore should only be used for mutual exclusion (mutex) purpose.
In this case, it would be impossible for 3 threads to wait (2 on aquire and 1 on release) at the same time, because the wait condition of release is never true.
We could write a catch all implementation with notifyAll, but it would have additional costs.
Also, semaphore is a programming construct, expected to be handled correctly by the caller.