I have three Producers P1,P2,P3 and Three consumers with single shared queue. Producer P1 will put/insert X1,X2,X3 into queue and it should be consumed only by Consumer C1 not other Consumers(C2,C3). Basically Consumers C1 should only consume values inserted by Producer P1. the same rule applies to rest of the consumers. C2-> P2 and C3->P3. How to solve this problem in Java.
Asked
Active
Viewed 199 times
0

nabster
- 1,561
- 2
- 20
- 32

kiran kumar Mudradi
- 11
- 2
-
1Create 3 queues. Why would you use a shared queue, if there is no sharing going on? – Andreas Oct 01 '18 at 17:33
-
1Are you trying to solve it purely with Java using data structures, multi-threading or can you use third party libraries? If yes then I would suggest Kafka and how you can use topic. Basically there is a queue (broker) with n topics with source (producers) and a sink (consumers). Your consumer can subscribe to a particular topic. – nabster Oct 01 '18 at 17:37
-
all of them should use/share same queue. and producers insert data randomly into the queue. consumers should take item from respective producers. can we do this in java. – kiran kumar Mudradi Oct 01 '18 at 17:40
-
Yes only with Java and data structures. – kiran kumar Mudradi Oct 01 '18 at 17:41
-
2Create a single consumer taking from the queue and distributing to the others after determining data item type. – daniu Oct 01 '18 at 17:56
-
What you have there is an esoteric programming puzzle. It's not a "problem" in the normal sense of the word. If your goal is to create reliable, maintainable software that solves some _real-world_ problem, and you think you need two or more threads to pull items from the same queue, then those threads should be completely interchangeable with each other. – Ohm's Lawman Oct 01 '18 at 18:58
1 Answers
0
The way this would be ultimately working is there would be a class like this
class Envelope<S, T, M> {
final S sender;
final T topic;
final M message;
...
};
All sent messages will be wrapped into it (like real letters in the envelopes) and posted into a MailBox
. Dispatcher at the other end of the mailbox will look at topic/receiver fields of the envelope and apply a required policy to deliver to a correct recipient in a correct context (thread).
As to coding it yourself — I would only do it for fun. If I needed something quickly I'd take Akka
that already has all required primitives and used them.

bobah
- 18,364
- 2
- 37
- 70