BlockingQueue - one producer multiple consumers

Tim Romanski :

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?

Glains :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216850&siteId=1