Home > Articles > Programming > Java

This chapter is from the book

The Java Message Service (JMS)

An enterprise-level platform such as J2EE wouldn't be complete without a messaging API. Thanks to the Java Message Service (JMS), J2EE has good support for messaging. JMS is similar to JDBC in that it is a standard API for existing message systems, just as JDBC is a standard API for accessing databases. Like JDBC, JMS can't stand on its own two feet. It only defines the interfaces and major classes that are used to communicate with a messaging system, and does not actually implement any messaging.

Most of the top J2EE application servers support messaging, so you shouldn't have too hard a time finding an implementation of the messaging service. Sun provides a list of JMS vendors at http://java.sun.com/products/jms/vendors.html.

JMS supports both point-to-point messaging and publish-subscribe. You send point-to-point messages using queues and you publish messages to subscribers via topics.

Note

Although JMS supports point-to-point and pub-sub messaging, the specification doesn't require a vendor to implement both types of messaging. A particular implementation might contain only point-to-point or pub-sub.


JMS seems a little complicated when you first start using it because it you must create a lot of classes just to send a message. After you understand the structure of the classes, however, it is easy to use. The QueueConnection and TopicConnection classes manage all your interactions with the message server, but to interact with the message server, you must create either a QueueSession or a TopicSession. Figure 19.6 shows the relationship between connections, sessions, queues, and topics.

Figure 19.6. Although the connection is your link to the message server, you do your work using other objects.

In many ways, JMS connections are like JDBC connections. They represent your connection to a server and you use them to create other objects, but you don't normally do your work by using them directly. The QueueSession and TopicSession classes are also similar to JDBC connections in that you use them to create objects, but again, you don't interact with them directly to send and receive messages.

The session objects let you create the senders, receivers, queues, and topics you need to actually send and receive messages.

One of the big benefits of JMS is that you can perform message operations as part of a transaction. When you create a QueueSession or a TopicSession, you can specify that the session is transactional. The reason transactions are so important for messaging is that you get into situations in which you read a message off a message queue and then try to insert the message in a database. If the database operation fails, you can't just stick the message back on the queue. If the operation is transactional, however, when the database operation fails, your message stays in the queue. Transactions can also ensure that the messaging system delivers the messages in the order you send them.

Sending Queue Messages

Before you can perform any kind of queue operations in JMS, you must first create a QueueConnection. You use JNDI to locate a QueueConnectionFactory and then create the connection. Next, you use the QueueConnection to create a QueueSession. Next, you create the Queue (although you usually look for the queue in the naming service first, in case someone has already created it). When you create the queue, you must give it a name. Every queue must have a unique name.

After you have a Queue, you're almost ready. All you need is a QueueSender to send messages on the queue and one or more Message objects. You use the QueueSession to create both the QueueSender and the messages.

Listing 19.1 shows a message queue version of the ever-popular "Hello World" program. In this case, the program sends "Hello" messages over a message queue.

Listing 19.1 Source Code for HelloQueueSender.java

package usingj2ee.messages;

import javax.jms.*;
import javax.naming.*;

public class HelloQueueSender
{
    public static void main(String[] args)
    {
        try
        {
// Locate the JNDI naming service
            Context ctx = new InitialContext();

// Locate the Queue Connection Factory via JNDI
            QueueConnectionFactory factory =
                (QueueConnectionFactory) ctx.lookup(
                    "javax.jms.QueueConnectionFactory");

// Create a new Queue Connection
            QueueConnection conn = factory.createQueueConnection();

// Create a Queue Session, ask JMS to acknowledge the messages
// The session is non-transactional; you don't send messages
// as part of a transaction.
            QueueSession session = conn.createQueueSession(false,
                Session.AUTO_ACKNOWLEDGE);

            Queue queue = null;

            try
            {
// See if someone has already created the queue
                queue = (Queue) ctx.lookup("HelloQueue");
            }
            catch (NameNotFoundException exc)
            {

// If not, create a new Queue and store it in the JNDI directory
                queue = session.createQueue("HelloQueue");
                ctx.bind("HelloQueue", queue);
            }

// Create a simple text message
            TextMessage message = session.createTextMessage("Hello Client!");

// Create a QueueSender (so you can send messages)
            QueueSender sender = session.createSender(queue);

// Tell the Queue Connection you are ready to interact with the message service
            conn.start();

            for (;;)
            {
// Send a message
                sender.send(message);

// Wait 5 seconds (5,000 milliseconds) before sending another message
                try { Thread.sleep(5000); } catch (Exception ignore) {}
            }
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}
						

Receiving Queue Messages

Most of the setup you do for sending messages is the same as for receiving them. Of course, instead of creating a QueueSender, you create a QueueReceiver. There are two different ways to receive messages. You can call the receive method, which waits for messages, or you can create a listener object that receives messages when they become available.

Listing 19.2 shows a simple message receiver that uses the receive method to retrieve the queue messages. Notice that most of the setup is the same as in Listing 19.1.

Listing 19.2 Source Code for HelloQueueReceiver.java

package usingj2ee.messages;

import javax.jms.*;
import javax.naming.*;

public class HelloQueueReceiver
{
    public static void main(String[] args)
    {
        try
        {
// Locate the JNDI naming service
            Context ctx = new InitialContext();

// Locate the Queue Connection Factory via JNDI
            QueueConnectionFactory factory =
                (QueueConnectionFactory) ctx.lookup(
                    "javax.jms.QueueConnectionFactory");

// Create a new Queue Connection
            QueueConnection conn = factory.createQueueConnection();

// Create a Queue Session, ask JMS to acknowledge the messages
// This program receives messages, so it doesn't really care.
// The session is non-transactional 

            QueueSession session = conn.createQueueSession(false,
                Session.AUTO_ACKNOWLEDGE);

            Queue queue = null;
            try
            {
// See if someone has already created the queue
                queue = (Queue) ctx.lookup("HelloQueue");
            }
            catch (NameNotFoundException exc)
            {
// If not, create a new Queue and store it in the JNDI directory
                queue = session.createQueue("HelloQueue");
                ctx.bind("HelloQueue", queue);
            }

// Create a QueueReceiver to receive messages
            QueueReceiver receiver = session.createReceiver(queue);

// Tell the Queue Connection you are ready to interact with the message service
            conn.start();

            for (;;)
            {
// Receive the next message
                TextMessage message = (TextMessage) receiver.receive();

// Print the message contents
                System.out.println(message.getText());
            }
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}
						

If you don't want to wait for messages, but instead prefer to have the QueueReceiver notify you when a message comes in, you can implement the MessageListener interface. You tell the QueueReceiver about your message listener and it will automatically let you know when a message comes in. Listing 19.3 shows the listener version of the message receiver in Listing 19.2.

Listing 19.3 Source Code for HelloQueueListener.java

package usingj2ee.messages;

import javax.jms.*;
import javax.naming.*;

public class HelloQueueListener implements MessageListener
{
    HelloQueueListener()
    {
    }

/** Called by the QueueReceiver to handle the next message in the queue */
    public void onMessage(Message message)
    {
        try
        {
// Assume the message is a text message
            TextMessage textMsg = (TextMessage) message;

// Print the message text
            System.out.println(textMsg.getText());
        }
        catch (JMSException exc)
        {
            exc.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        try
        {
// Locate the JNDI naming service
            Context ctx = new InitialContext();

// Locate the Queue Connection Factory via JNDI
            QueueConnectionFactory factory =
                (QueueConnectionFactory) ctx.lookup(
                    "javax.jms.QueueConnectionFactory");

// Create a new Queue Connection
            QueueConnection conn = factory.createQueueConnection();

// Create a non-transactional Queue Session
            QueueSession session = conn.createQueueSession(false,
                Session.AUTO_ACKNOWLEDGE);

            Queue queue = null;
            try
            {
// See if someone has already created the queue
                queue = (Queue) ctx.lookup("HelloQueue");
            }
            catch (NameNotFoundException exc)
            {
// If not, create a new Queue and store it in the JNDI directory
                queue = session.createQueue("HelloQueue");
                ctx.bind("HelloQueue", queue);
            }

// Create a QueueReceiver to receive messages
            QueueReceiver receiver = session.createReceiver(queue);

// Tell the Queue Connection you are ready to interact with the message service
            conn.start();


// Tell the receiver to call your listener object when a new message arrives
            receiver.setMessageListener(new HelloQueueListener());

// Normally you would do other processing here...
            Thread.sleep(999999999);
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}
						

You typically have one queue receiver and one or more queue senders. Although JMS allows you to have multiple receivers on a queue, it is up to the individual implementations to decide how to handle multiple receivers. Some might distribute the messages evenly across all receivers, and others might just send all the messages to the first receiver you create.

Note

Because sessions are single-threaded, you can only process one message at a time. If you need to process multiple messages concurrently, you must create multiple sessions.


Publishing Messages

Although the overall concept of publish-subscribe is a bit different from point-to-point messages, the JMS calls for creating a topic and publishing messages are remarkably similar to the calls for sending queue messages. In fact, if you go through the program in Listing 19.1 earlier in this chapter and change all the occurrences of Queue to Topic, you'll almost have a working topic publisher. You must also change the createSender call to createPublisher.

As with queues, each topic must have a unique name. Unlike queues, in which you only have one receiver, you normally have many subscribers to a topic. You can also have multiple publishers.

Listing 19.4 shows the publish-subscribe version of the ubiquitous "Hello World," at least the publishing half.

Listing 19.4 Source Code for HelloTopicPublisher.java

package usingj2ee.messages;

import javax.jms.*;
import javax.naming.*;

public class HelloTopicPublisher
{
    public static void main(String[] args)
    {
        try
        {
// Locate the JNDI naming service
            Context ctx = new InitialContext();

// Locate the Topic Connection Factory via JNDI
            TopicConnectionFactory factory =
                (TopicConnectionFactory) ctx.lookup(
                    "javax.jms.TopicConnectionFactory");

// Create a new Topic Connection
            TopicConnection conn = factory.createTopicConnection();

// Create a non-transactional TopicSession
            TopicSession session = conn.createTopicSession(false,
                Session.AUTO_ACKNOWLEDGE);

            Topic topic = null;

            try
            {
// See if someone has already created the topic
                topic = (Topic) ctx.lookup("HelloTopic");
            }
            catch (NameNotFoundException exc)
            {
// If not, create a new topic and store it in the JNDI directory
                topic = session.createTopic("HelloTopic");
                ctx.bind("HelloTopic", topic);
            }

// Create a new text message
            TextMessage message = session.createTextMessage("Hello Client!");

// Create a publisher to publish messages
            TopicPublisher sender = session.createPublisher(topic);

// Tell the Topic Connection you are ready to interact with the message service
            conn.start();

            for (;;)
            {
// Publish the message
                sender.publish(message);

// Wait 5 seconds before sending another message
                try { Thread.sleep(5000); } catch (Exception ignore) {}
            }
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}
						

You can run multiple copies of this program with no problems. Your clients will just see more messages than they do if only one copy is running.

Subscribing to Topics

Subscribing to a topic is just as easy as listening on a queue. Again, you can just about convert the program in Listing 19.2 earlier in the chapter to work with topics just by changing all the occurrences of Queue to Topic. Listing 19.5 shows the subscriber for the "Hello World" pub-sub example.

Listing 19.5 Source Code for HelloTopicReceiver.java

package usingj2ee.messages;

import javax.jms.*;
import javax.naming.*;

public class HelloTopicReceiver
{
    public static void main(String[] args)
    {
        try
        {
// Locate the JNDI naming service
            Context ctx = new InitialContext();

// Locate the Topic Connection Factory via JNDI
            TopicConnectionFactory factory =
                (TopicConnectionFactory) ctx.lookup(
                    "javax.jms.TopicConnectionFactory");

// Create a new Topic Connection
            TopicConnection conn = factory.createTopicConnection();

// Create a non-transactional Topic Session
            TopicSession session = conn.createTopicSession(false,
                Session.AUTO_ACKNOWLEDGE); 

            Topic topic = null;
            try
            {
// See if someone has already created the topic
                topic = (Topic) ctx.lookup("HelloTopic");
            }
            catch (NameNotFoundException exc)
            {
// If not, create a new topic and store it in the JNDI directory
                topic = session.createTopic("HelloTopic");
                ctx.bind("HelloTopic", topic);
            }

// Create a subscriber to receive messages
            TopicSubscriber subscriber = session.createSubscriber(topic);

// Tell the Topic Connection you are ready to interact with the message service
            conn.start();

            for (;;)
            {
// Get the next published message
                TextMessage message = (TextMessage) subscriber.receive();

// Print the message text
                System.out.println(message.getText());
            }
        }
        catch (Exception exc)
        {
            exc.printStackTrace();
        }
    }
}
						

As with the QueueReceiver class, you can choose to receive message notifications asynchronously by using the MessageListener interface. The actual listener implementation for topics is identical to the one for queues.

Durable Subscriptions

Most pub-sub systems you see today deal with frequently published data and tend to provide real-time monitoring and status updates. Pub-sub is good for these kinds of operations. Many pub-sub implementations have a peculiar limitation that makes them only suitable for applications with frequently published data-more specifically, applications in which it doesn't matter if you miss a message because there will be another one in a few minutes.

The reason pub-sub usually only works in these types of applications is that pub-sub doesn't usually have the concept of a persistent, or durable subscription. For example, suppose you are publishing flight cancellations for LaGuardia Airport. Although it's true that they do seem to occur often enough that there will be another one in a few minutes, you really don't want to miss one. Now, suppose you have a program that makes a list of passengers who need to be rebooked for the next available flight (tomorrow, next week, sometime next year, and so on). If the program shuts down for a few minutes, it might miss three or four cancel lations! You want the message server to hold on to your messages while your program is down.

JMS supports durable subscription. After you create a durable subscription, the JMS server keeps any messages you miss while your program isn't running. To create a durable subscription, use the createDurableSubscriber method in the TopicSession class:

						
public TopicSubscriber createDurableSubscriber(Topic topic,
    String subscriptionName)

You must always use the same subscription name when reconnecting your program to its durable subscription. That is, if you call the subscription RebookFlightCx (that's the subscription name, not the topic name), you must always ask for RebookFlightCx when resuming that subscription. Keep in mind that durable connections are expensive for the server to maintain, so only use them when absolutely necessary.

Messages can have an expiration time, so when a message expires, the server can safely remove it from the durable subscription. This helps keep the database size down when you don't resume a durable subscription for a long time.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020