I have developed a simple pubsub event subscription in java. Something similar to this thread
These are the goals.
- Class should be able to "listen" to events happening in the module.
- It should be disconnected from the event emitter. That is, the listeners shouldn't have to know which classes may be emitting events.
- All the subscribers should be notified parallelly.
My Broker.java
import java.util.*;
public final class Broker {
private Object mutex = new Object();
static class CommonTopics{
private CommonTopics(){}
public static final String ON_CACHE_RESET = "onCacheReset";
}
private static Broker brokerInstance;
private Broker(){
}
public static Broker getInstance(){
if(null== brokerInstance){
brokerInstance = new Broker();
}
return brokerInstance;
}
private Map<String, Set<Subscriber>> subscribers = new HashMap<>();
public boolean deregister(String topic, Subscriber subscriber) {
synchronized (mutex) {
final Set<Subscriber> subs = this.subscribers.get(topic);
return subs.remove(subscriber);
}
}
public boolean register(String topic, Subscriber subscriber) {
boolean returnVal;
synchronized (mutex) {
if (subscribers.containsKey(topic)) {
returnVal = subscribers.get(topic).add(subscriber);
} else {
Set<Subscriber> sub = new HashSet<>();
returnVal = sub.add(subscriber);
subscribers.put(topic, sub);
}
}
return returnVal;
}
public void sendMessage(String topic,Map map){
synchronized (mutex) {
final Set<Subscriber> sub = this.subscribers.get(topic);
sub.parallelStream().forEach(subscriber -> subscriber.update(map));
}
}
}
My Subscriber interface
import java.util.Map;
public interface Subscriber {
public void update(Map map);
}
And an example subscriber
import java.util.Map;
public class ExampleSubscriber implements Subscriber {
@Override
public void update(Map map) {
System.out.println(map.get("oldCachedValue"));
System.out.println(map.get("newCachedValue"));
}
public static void main(String[] args) {
ExampleSubscriber subscriber = new ExampleSubscriber();
Broker.getInstance().register(Broker.CommonTopics.ON_CACHE_RESET,subscriber);
}
}
Example event emmitter
Map m = new HashMap();
m.put("oldCachedValue","Yes");
m.put("newCachedValue","No");
Broker.getInstance().sendMessage(Broker.CommonTopics.ON_CACHE_RESET,m);
Subscriber.update(Map)
, namelyMap
, which is probably not a good idea. However, I don't know what the purpose of thisMap
is, so I cannot suggest an alternative. What does thisMap
represent? \$\endgroup\$