implement-your-own blocking queue in java

后端 未结 4 1011
日久生厌
日久生厌 2021-02-02 00:01

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.

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 00:12

    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)

提交回复
热议问题