0

I need a blocking queue that has a size of 1, and every time put is applied it removes the last value and adds the next one. The consumers would be a thread pool in which each thread needs to read the message as it gets put on the queue and decide what to do with it, but they shouldn't be able to take from the queue since all of them need to read from it.

I was considering just taking and putting every time the producer sends out a new message, but having only peek in the run method of the consumers will result in them constantly peeking, won't it? Ideally the message will disappear as soon as the peeking stops, but I don't want to use a timed poll as it's not guaranteed that every consumer will peek the message in time.

My other option at the moment is to iterate over the collection of consumers and call a public method on them with the message, but I really don't want to do that since the system relies on real time updates, and a large collection will take a while to iterate through completely if I'm going through each method call on the stack.

adnan_252
  • 411
  • 2
  • 4
  • 10
  • Can't you subclass or decorate an existing queue to accomplish that? – Alexander Kulyakhtin Apr 18 '14 at 05:05
  • Just to be clear - if the producer turns up and not all the consumer thread have read the single buffer, you want it to block until the have, yes? – Martin James Apr 18 '14 at 08:56
  • @MartinJames yes, hopefully that won't be too much of an issue as the consumers are all individual threads. They could just only read the tail, but that will probably result in a stack overflow when a certain number of messages have been added – adnan_252 Apr 18 '14 at 09:24
  • Also just to be clear, consumers will block if the message is still the one they got previously, even though the producer has a next message available, but is blocked since not all clients have peeked? – bowmore Apr 18 '14 at 09:47
  • @bowmore yeah that would have to be the case. The consumers would have to peek the queue, blocking it, then releasing its control for the rest of the consumers. I might have to resort to implementing observer interfaces for the consumers, but it'll mean rewriting the producer code too – adnan_252 Apr 18 '14 at 10:57

1 Answers1

1

After some consideration, I think you're best off, with each consumer having its own queue and the producer putting its messages on all queues.

  • If there are few consumers, then putting the messages on those few queues will not take too long (except when the producer blocks because a consumer can't keep up).
  • If there are many consumers this situation will be highly preferable over a situation where many consumers are in contention with each other.

At the very least this would be a good measure to compare alternate solutions against.

bowmore
  • 10,842
  • 1
  • 35
  • 43