In Java Concurrency In Practice book (p.156), there's a statement regarding poison pill approach:
Poison pills work reliably only with unbound queues.
Does it mean that with a bounded queue I can get a deadlock, or is it about some other liveness problems? Is it connected with number of producers and customers?
The term poison pill refers to a defensive technique used by a target firm to avoid or deter an acquiring business from taking the risk of a hostile takeover. Prospective targets use this strategy to make the potential acquirer appear less appealing to them.
A bounded queue is a queue limited to a fixed number of items. There are several efficient implementations of FIFO queues. An efficient implementation is one that can perform the operations—en-queuing and de-queuing—in O(1) time. Linked list.
A blocking queue is defined as a queue which blocks the caller of the enqueue method if there's no more capacity to add the new item being enqueued. Similarly, the queue blocks the dequeue caller if there are no items in the queue.
With a bounded queue, you could be prevented from adding the poison pill.
One way to avoid this issue is to make the bounded queue allow one more when a poison pill is added.
The problem is that the queue may be full at close time.
It depends on how valuable the data in the queue is at the time of closure. Can you afford to throw everything in the queue away?
When the time comes to close the queue it should be effective to drain the queue first before adding the poison pill.
void close () throws InterruptedException {
do {
// Empty the queue.
while ( queue.poll(0,TimeUnit.MILLISECONDS) != null ) {
// Throw it away.
}
// Keep draining the queue 'till the pill is swallowed.
} while (!queue.offer(STOP, 0, TimeUnit.MILLISECONDS)) ;
}
but of course if the items in the queue are valuable you may wish to use drainto
and preserve them.
Please also bear in mind that there may be more items added to the queue after the poison pill because not only might the queue be full but there may also be threads blocked waiting to post to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With