In producer-consumer model (one thread producing items, putting it in a blocking queue and another thread consuming them in an endless loop) it's recommended to shutdown the threads by sending a poison object which causes the loop to break.
Afaik, this can be done by using:
null
(discouraged in general and forbidden byBlockingQueue
)- a value which won't ever be created by the producer (requires extra testing and maybe vaporizing some brain cells)
- a wrapper type and put every produced value in a class which contains the value as only property and is set to null in order to indicate shutdown (e.g.
Optional
of the Guava framework) (requires expensive allocation of an object for every produced item) - an extra property added to the class which is used as item type (makes the model quite unflexible)
- a subclass of the type created by producer which is only used for the poison object (doesn't work with final classes, requires an extra class which can be private and doesn't consume noticable space, but is a drawback)
- interrupting the thread doesn't allow to clear the queue.
I'm looking for a type-safe solution for arbitrary queue items.
object
which you can check for reference-equality? Like in your Producer you havepublic static object POISON = new object();
and in your consumer you checkwhile (objFromQueue != Producer.POISON) { do your stuff }...
– Fildor