Broadcast

In some applications, it is necessary to broadcast the same message to multiple sessions. For example when publishing market-data from an exchange.

This could be achieved inefficiently by iterating over sessions in the application, but Babl provides a mechanism for publishing a single message from the application, that will be routed to multiple sessions in the Session Container.

Broadcasting via Topics

Broadcasting messages is achieved by managing topics from the application. The application is responsible for creating, deleting and management of topic membership.

When the application sends a message to a topic, it is intercepted by all session containers, and published to sessions that are a member of the specified topic.

Using Broadcast

To use the broadcast function, your application class should implement the BroadcastSource interface.

When Babl is launched, your application will be provided with an implementation of the Broadcast interface that can be used for topic management and the sending of broadcast messages.

An example of using broadcast can be seen below:

private static final class MarketDataApplication
    implements Application, BroadcastSource
{
    private Broadcast broadcast;

    @Override
    public void setBroadcast(final Broadcast broadcast)
    {
        // store the Broadcast implementation
        this.broadcast = broadcast;
        // create a topic for broadcast
        broadcast.createTopic(MARKET_DATA_TOPIC_ID);
    }

    @Override
    public int onSessionConnected(final Session session)
    {
        // add new sessions to the topic
        broadcast.addToTopic(MARKET_DATA_TOPIC_ID, session.id());
        return SendResult.OK;
    }

    public void onMarketDataUpdate(final MarketDataUpdate update)
    {
        final DirectBuffer buffer = serialise(update);
        // send a message to all sessions registered on the topic
        broadcast.sendToTopic(MARKET_DATA_TOPIC_ID, buffer, 0, buffer.capacity());
    }
}