Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top