I know this question has been asked and answered many times before, but I just couldn\'t figure out a trick on the examples found around internet, like this or that one.
The reason why the authors used notifyAll()
is simple: they had no clue whether or not it was necessary, so they decided for the "safer" option.
In the above example it would be sufficient to just call notify()
as for each single element added, only a single thread waiting can be served under all circumstances.
This becomes more obvious, if your queue as well has the option to add multiple elements in one step like addAll(Collection
, as in this case more than one thread waiting on an empty list could be served, to be exact: as many threads as elements have been added.
The notifyAll()
however causes an extra overhead in the special single-element case, as many threads are woken up unnecessarily and therefore have to be put to sleep again, blocking queue access in the meantime. So replacing notifyAll()
with notify()
would improve speed in this special case.
But then not using wait/notify and synchronized at all, but instead use the concurrent package would increase speed by a lot more than any smart wait/notify implementation could ever get to.