Enterprise applications can use the JMS to communicate to outside applications or other application servers. EJBs can use JMS to decouple communication with these other systems in an asynchronous manner using a publish/subscribe (pub/sub) pattern. JMS message topics create a one (the sender) to many (the receiver) relationship between messaging partners. In addition, pub/sub topics can be used to store messages even when no entity is ready to retrieve them (referred to as durable subscriptions).

To send a message to a JMS topic, you first need to create a JNDI context and retrieve the JMS connection factory for topics in the JMS environment. Next, you must create a topic connection in order to establish a topic session. Once you have a session, you can find the actual topic to which you want to send a message, and build a publisher object for transmission of your message.

public class MessagePublisher {
    
    ...
            
    private void publish(String subject, String content) {
        
        try {
            
            // first configure and retreive initial context:
            InitialContext context = getInitialContext();
            
            // get the topic factory:
            TopicConnectionFactory factory = (TopicConnectionFactory)
            context.lookup("TopicFactory");
            
            // create a topic connection and session:
            TopicConnection connection = factory.createTopicConnection();
            TopicSession session = connection.createTopicSession(
                    false, Session.AUTO_ACKNOWLEDGE);
            
            // finds the topic and build a publisher:
            Topic topic = (Topiccontext.lookup("SampleTopic");
            TopicPublisher publisher = session.createPublisher(topic);
            
            // finally, create and publish a message:
            MapMessage message = session.createMapMessage();
            
            message.setString("Subject", subject);
            message.setString("Content", content);
            
            publisher.publish(message);
            
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    ...
}