How to block until a BlockingQueue is empty?

前端 未结 6 2156
逝去的感伤
逝去的感伤 2021-02-02 10:30

I\'m looking for a way to block until a BlockingQueue is empty.

I know that, in a multithreaded environment, as long as there are producers putting items in

6条回答
  •  忘掉有多难
    2021-02-02 10:57

    Your use case should be quite special because most typically you would only want to block the producer when the queue is full, but not wait until it is empty.

    Anyway, this is doable. I believe that spinning until isEmpty returns true is not THAT inefficient because the producer will be locally spinning, i.e., will be accessing its own cache, not banging the bus. It will however be consume CPU time as the thread remains schedulable. But local spinning is definitely the easier way. Otherwise I see two options:

    1. Using wait + notify like @niculare suggested
    2. Somehow make the first consumer that notices the queue empty to notify the producer in a lock-free way; this will be slower but degrade "more" gracefully

提交回复
热议问题