I am new to Java and had some difficulty creating this simple Publisher Subscriber class. It finally seems to be working and I wanted to check if I have been following best practices and see if there are any improvements I can make.
The following Java class accepts any topics as a string (e.g. "rand_int") and forwards any messages to that topic to any subscribers.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
public class PubSub {
private Map<String, ArrayList<Consumer<?>>> topicsSubscribers =
new HashMap<String, ArrayList<Consumer<?>>>();
private static PubSub pubSubSingleton = null;
public static PubSub getInstance() {
if (pubSubSingleton == null)
pubSubSingleton = new PubSub();
return pubSubSingleton;
}
public <T> void publish(String topic, T message) {
ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topic);
if (subscribers == null)
return;
for (Consumer subscriberConsumer : subscribers) {
subscriberConsumer.accept(message);
}
}
public synchronized <T> void subscribe(String topicName, Consumer<T> subscriberCallback) {
ArrayList<Consumer<?>> subscribers = this.topicsSubscribers.get(topicName);
if (subscribers == null) {
subscribers = new ArrayList<Consumer<?>>();
subscribers.add(subscriberCallback);
this.topicsSubscribers.put(topicName, subscribers);
} else {
subscribers.add(subscriberCallback);
}
}
}
Example usage:
public class SomeClass {
public SomeClass() {
PubSub.getInstance().subscribe("rand_int", this::randIntCallback);
PubSub.getInstance().publish("rand_int", 46);
}
public randIntCallback(int number) {
System.out.println(number);
}
}
The above code should output "46".
As I said, I am very new to Java and would like some feedback on my code to help improve. So any help on this is very appreciated.