Search code examples
java.netdesign-patternspublish-subscribe

Does Publisher and Subscriber is on same thread


This is for just get an clarification on pub/sub + threading.

Doubt I have is In normal publisher/subscriber pattern does both subscribers and publisher is running on same thread or in different threads?

Or is it depend on implementations?

What I have in mind so far is different subscription would have it is own threads whereas publisher run on it is own thread?


Solution

  • In normal publisher/subscriber pattern, does both subscribers and publisher is running on same thread or in different threads ? Or is it depend on implementations ?

    In general, Publisher/Subscriber runs in different threads. Here, these publisher/subscriber threads could be within the same application or it could be from a different application running outside of your project. Like for example, your application might publish some data about products information and the other application might subscribe to that data and use it.

    There are several ways that you can implement producer/consumer based application like using Queue or using JMS (which loosely couples both producer and consumer with more features), etc.. Typically in these implementations, messages will be published by the publishers producing messages from one thread (with/different application) and consumers consumes messages from other end.

    What I have in mind so far is different subscription would have it is own threads whereas publisher run on it is own thread ?

    Yes, you are right and adding to that don't assume that there will be only one publisher always. In some of the real world applications, there could be several producers (running in different threads) publishing the messages and several consumers (running in different threads) consuming those messages.