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.
I think logically there is no harm doing that extra check before notifyAll()
.
You can simply notifyAll()
once you put/get something from the queue. Everything will still work, and your code is shorter. However, there is also no harm checking if anyone is potentially waiting (by checking if hitting the boundary of queue) before you invoke notifyAll()
. This extra piece of logic saves unnecessary notifyAll()
invocations.
It just depends on you want a shorter and cleaner code, or you want your code to run more efficiently. (Haven't looked into notifyAll()
's implementation. If it is a cheap operation if there is no-one waiting, the performance gain may not be obvious for that extra checking anyway)