How to immediately release threads waiting on a BlockingQueue

Joel Shemtov picture Joel Shemtov · Jul 22, 2010 · Viewed 7.9k times · Source

Consider a BlockingQueue and a few threads waiting on poll(long, TimeUnit) (possibly also on on take()).

Now the queue is empty and it is desired to notify the waiting threads that they can stop waiting. The expected behaviour is to have either null returned or the declared InterruptedException thrown.

Object.notify() won't work for LinkedBlockingQueue as the threads are waiting on an internal lock.

Any straightforward way?

Answer

unbeli picture unbeli · Jul 22, 2010

Javadoc for the BlockingQueue suggests a good way:

A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation to indicate that no more items will be added. The needs and usage of such features tend to be implementation-dependent. For example, a common tactic is for producers to insert special end-of-stream or poison objects, that are interpreted accordingly when taken by consumers.