I have a number of concurrent clients – i.e. threads running and doing something concurrently.
Each client implements a listener of some event bus.
A message from that bus can arrive to one or more clients.
My task is to broadcast that message to all the clients.
This task seems simple, but I cannot find a solution which is not ugly in some way.
(1) The straightforward solution:
void onMessageArrived(Message message) {
broadcast(message);
}
- is bad because each message will be broadcasted for many times because several clients can receive that message, and thus several onMessageArrived handlers can run.
(2) We can store the broadcasted messages in some list:
void onMessageArrived(Message message) {
if (alreadyBroadcastedConcurrentMap.putIfAbsent(message)==null) {
broadcast(message);
}
}
- this solves the previously mentioned problem, but many clients will repeat the useless operation of putting the already existing message into that list.
But may be there are some better options?
Java.
Your design contains flaws, or it is badly explained. Either you want to broadcast to all clients, or multicast to a selected list. It doesn’t make sense to specify some recipients and then make each recipient responsible for delivering it to all the other clients, handling duplications and races by hand. Just make all clients listening to the bus, possibly ignoring messages.
I’d introduce a new central
BroadcasterObviously each client will have to register to this broadcast domain
and just forget about multiple delivery. You can go further and simulate a LAN by using multiple broadcast domains, if the number of clients is huge and you have other very strict requirements – which I don’t think you have