Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use poison pill approach with bounded queues?

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?

like image 488
Boris Treukhov Avatar asked Dec 29 '11 12:12

Boris Treukhov


People also ask

What is poison pill in software?

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.

What is a bounded queue?

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.

What is bounded blocking queue?

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.


2 Answers

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.

like image 113
Peter Lawrey Avatar answered Oct 14 '22 00:10

Peter Lawrey


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.

like image 32
OldCurmudgeon Avatar answered Oct 14 '22 00:10

OldCurmudgeon