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.