Publish-Subscribe

Other topics

Publish-Subscribe in Java

The publisher-subscriber is a familiar concept given the rise of YouTube, Facebook and other social media services. The basic concept is that there is a Publisher who generates content and a Subscriber who consumes content. Whenever the Publisher generates content, each Subscriber is notified. Subscribers can theoretically be subscribed to more than one publisher.

Usually there is a ContentServer that sits between publisher and subscriber to help mediate the messaging

public class Publisher {
    ...
    public Publisher(Topic t) {
        this.topic = t;
    }

    public void publish(Message m) {
        ContentServer.getInstance().sendMessage(this.topic, m);
    }
}

public class ContentServer {
    private Hashtable<Topic, List<Subscriber>> subscriberLists;

    private static ContentServer serverInstance;

    public static ContentServer getInstance() {
        if (serverInstance == null) {
            serverInstance = new ContentServer();
        }
        return serverInstance;
    }

    private ContentServer() {
        this.subscriberLists = new Hashtable<>();
    }
    
    public sendMessage(Topic t, Message m) {
        List<Subscriber> subs = subscriberLists.get(t);
        for (Subscriber s : subs) {
            s.receivedMessage(t, m);
        }
    }

    public void registerSubscriber(Subscriber s, Topic t) {
        subscriberLists.get(t).add(s);
    }

public class Subscriber {
    public Subscriber(Topic...topics) {
        for (Topic t : topics) {
            ContentServer.getInstance().registerSubscriber(this, t);
        }
    }
    
    public void receivedMessage(Topic t, Message m) {
        switch(t) {
            ...
        }
    }
}

Usually, the pub-sub design pattern is implemented with a multithreaded view in mind. One of the more common implementations sees each Subscriber as a separate thread, with the ContentServer managing a thread pool

Simple pub-sub example in JavaScript

Publishers and subscribers don't need to know each other. They simply communicate with the help of message queues.

(function () {
        var data;

        setTimeout(function () {
            data = 10;
            $(document).trigger("myCustomEvent");
        }, 2000);

        $(document).on("myCustomEvent", function () {
            console.log(data);
        });
})();

Here we published a custom event named myCustomEvent and subscribed on that event. So they don't need to know each other.

Contributors

Topic Id: 7260

Example Ids: 6498,29689

This site is not affiliated with any of the contributors.