1

I have three threads. Thread 1 (T1) is the producer, which generates data. Threads 2 an 3 (T2, T3 respectively) each wait on T1's data to process in separate loops. I'm thinking of sharing a BlockingQueue between the threads and having T2 and T3 wait by calling "take".

The docs for java.util.concurrent.BlockingQueue say it can "safely be used with multiple producers and multiple consumers". Trying out the example from the docs, it seems as though the behaviour is to allow one consumer to "take" the "put" object instead of all of them receiving it. So, either T2 or T3 gets the data and it appears as though they alternate. I'd like both of them to get the same data when T1 puts some data.

My question is, is BlockingQueue the right way to go? Should I be thinking about this problem differently?

Tim Romanski
  • 111
  • 1
  • 7
  • Usually in a queue one and only one consumer gets one element from the queue. Line in a supermarket you get served by only one cashier not but every cashier. If you want each item produced by T1 being processed twice (once by T2 and once by T3) you will need a separate queue for each consumer. – Ivan Mar 11 '20 at 04:33

1 Answers1

2

Sounds like Publish-Subscribe, you publish data to a topic and all registered consumers receive a copy of the message. In contrast, a queue delivers a message to a single registered consumer only. I recommend you reconsider the desin of that component.

The BlockingQueue, essentailly a Queue implementation, as the name suggests, is a queue which allows to add and examine objects. These operations are thread-safe, which means that for example no two threads receive the same object when examining.

Glains
  • 2,773
  • 3
  • 16
  • 30
  • Thanks! For anyone curious, I implemented a Pub/Sub, each subscriber with their own BlockingQueue. Publishers call 'put' on publish, subscribers wait by 'take'-ing from their respective BlockingQueues. – Tim Romanski Mar 11 '20 at 21:09