Search code examples
javamultithreadingproducer-consumer

BlockingQueue: how can multiple producers stop a single consumer?


I wrote a producer/consumer based program using Java's BlockingQueue. I'm trying to find a way to stop the consumer if all producers are done. There are multiple producers, but only one consumer.

I found several solutions for the "one producer, many consumers" scenario, e.g. using a "done paket / poison pill" (see this discussion), but my scenario is just the opposite.

Are there any best practice solutions?


Solution

  • The best-practice system is to use a count-down latch. Whether this works for you is more interesting.....

    Perhaps each producer should register and deregister with the consumer, and when all producers are deregistered (and the queue is empty) then the consumer can terminate too.