Intraprocess Pub-Sub

18 Feb

Pub-Sub Overview

In computer science the term “pub-sub” is short for the Publish-Subscribe pattern of communication. In this pattern messages are produced by publishers and are not intended for any specific consumer. Instead, subscribers subscribe a class of messages and consume them. This provides a nice decoupling between the producers of messages and the consumers of messages. The term comes from — I assume — the newspaper or magazine industry where papers are published and subscribers read the papers, but the publisher is unaware of who specifically is reading the paper.

Intraprocess Pub-Sub

Communicating messages between two processes (possibly on different machines) seems like an obvious thing to do, and using the pub-sub pattern seems like a useful mechanism… but why do it intraprocess? For the same reasons you’d use it interprocess. Imagine a GUI that must track actions performed by the user. If a user clicks that produces a message and the message is published. Subscribers can then chose to subscribe to that “on-click” event and perform some action. In Java the subscribers must implement the EventListener interface to receive these messages.

The Guava EventBus

To use the pub-sub pattern in your own program, the SOP is to use the Guava EventBus. EventBus uses annotations on methods to register subscribers and routes messages to subscribers based upon type.
Messages are published to the EventBus by simply calling the post() method. A complete example of a producer that generates integers and two consumers who consume them can be found on github.

The last thing to note about EventBus is that subscribers must consume messages quickly or else they block everyone else down-stream from consuming messages. To make life easier, there is also an AsyncEventBus that will call each of the @Subscribe methods in their own thread.

If you have any questions, please post them in the comments. If you find and fix any bugs or have improvements, please fork and make a pull request.

Thanks for reading…

Leave a Reply

Your email address will not be published.