Skip to main content

If you don't have an IBM ID and password, register here.

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. This profile includes the first name, last name, and display name you identified when you registered with developerWorks. Select information in your developerWorks profile is displayed to the public, but you may edit the information at any time. Your first name, last name (unless you choose to hide them), and display name will accompany the content that you post.

All information submitted is secure.

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

Introducing the Java Message Service

author photo
Willy Farrell is a senior software engineer in the IBM Developer Skills Program. As part of the developerWorks team, he provides relevant technical information and insight to developers on the latest e-business and industry trends through Web content, articles, speaking engagements, and consulting to faculty at IBM Scholars Program member universities. He has been programming computers for a living since 1981, began using Java in 1996, and joined IBM in 1998.

Summary:  This tutorial provides an introductory overview of the Java Message Service, its functionality, and its capabilities. You will learn the basic programming techniques for creating JMS programs and work with sample code that demonstrates these techniques. Note: This tutorial has been updated to include changes to JMS version 1.1.

Date:  08 Jun 2004
Level:  Introductory PDF:  A4 and Letter (157 KB | 44 pages)Get Adobe® Reader®

Comments:  

Client programming with common interfaces

Client programming with common interfaces introduction

In this section, we'll walk through two programs that do JMS client messaging -- Sender.java and Receiver.java.

We'll look at the code in small sections and describe what each section does. You can see the complete listings in the Appendix: Code listing for Sender.java and Code listing for Receiver.java.

Sender: Prompt for JNDI names

All of the sample programs are command-line programs that use System.in for input and System.out for output.

The Sender class has two methods: main(String[]) and send(). The main(String[]) method merely instantiates a Sender and calls its send() method.

The first section of the send() method prompts for the JNDI names of the administered objects that will be used to send messages.

import java.io.*;
import javax.jms.*;
import javax.naming.*;

public class Sender {

    public static void main(String[] args) {

        new Sender().send();
    }

    public void send() {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        try {
            //Prompt for JNDI names
            System.out.println("Enter ConnectionFactory name:");
            String factoryName = reader.readLine();
            System.out.println("Enter Destination name:");
            String destinationName = reader.readLine();
    . . .


Sender: Look up administered objects

The next section of the send() method looks up the administered objects in JNDI, using the names input earlier.

JNDI is accessed by instantiating an InitialContext object; the administered objects are retrieved by calling the lookup(String) method, passing in the name of the object to be retrieved. Note that the lookup(String) method returns Object, so a typecast must be performed on the returned object.

    . . .
            //Look up administered objects
            InitialContext initContext = new InitialContext();
            ConnectionFactory factory =
                (ConnectionFactory) initContext.lookup(factoryName);
            Destination destination = (Destination) initContext.lookup(destinationName);
            initContext.close();
            . . .


Sender: Create JMS objects

Now, we create the JMS objects we need to send messages. Note that we don't directly instantiate these objects using new. All of the objects are created by calling a method on another object.

First, we use the ConnectionFactory to create a Connection. We then use that Connection to create a Session.

The Session is not transacted ( false ) and will use automatic acknowledgment ( Session.AUTO_ACKNOWLEDGE ).

Finally, we create the Sender to send messages to the Destination we retrieved from JNDI.

    . . .
            //Create JMS objects
            Connection connection = factory.createConnection();
            Session session =
                connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer sender = session.createProducer(destination);
            . . .


Sender: Send messages

Now we're ready to send messages. In this section, we enter a loop where we prompt for the text of a message to send. If the user types quit, the loop exits.

Otherwise, we build a TextMessage from the entered text and use the MessageProducer to send the message, then return to the top of the loop.

    . . .
            //Send messages
            String messageText = null;
            while (true) {
                System.out.println("Enter message to send or 'quit':");
                messageText = reader.readLine();
                if ("quit".equals(messageText))
                    break;
                TextMessage message = session.createTextMessage(messageText);
                sender.send(message);
            }
            . . .


Sender: Exit

Once the loop exits, we close the Connection. Closing the Connection automatically closes the Session and MessageProducer.

    . . .
            //Exit
            System.out.println("Exiting...");
            reader.close();
            connection.close();
            System.out.println("Goodbye!");

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}


Receiver: Prompt for JNDI names and look up administered objects

The Receiver class, like the Sender class, has a main(String[]) method that simply instantiates a Receiver and calls its primary method, receive().

The code for prompting for JNDI names and doing the lookup of administered objects is identical to that in Sender.

There are two differences in this class, however:

  • The boolean stop instance variable is used to indicate that the program should exit.

  • Receiver implements the MessageListener interface in order to receive messages asynchronously.

import java.io.*;
import javax.jms.*;
import javax.naming.*;

public class Receiver implements MessageListener {

    private boolean stop = false;

    public static void main(String[] args) {

        new Receiver().receive();
    }

    public void receive() {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        try {
            //Prompt for JNDI names
            System.out.println("Enter ConnectionFactory name:");
            String factoryName = reader.readLine();
            System.out.println("Enter Destination name:");
            String destinationName = reader.readLine();
            reader.close();

            //Look up administered objects
            InitialContext initContext = new InitialContext();
            ConnectionFactory factory =
                (ConnectionFactory) initContext.lookup(factoryName);
            Destination destination = (Destination) initContext.lookup(destinationName);
            initContext.close();
            . . .


Receiver: Create JMS objects

The Connection and Session are created as they are in Sender, and then a MessageConsumer is created.

Next, setMessageListener() is called, passing in this -- the local instance of Receiver, which you will recall implements the MessageListener interface.

Finally, the Connection is started to allow messages to be received.

    . . .
            //Create JMS objects
            Connection connection = factory.createConnection();
            Session session =
                connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageConsumer receiver = session.createConsumer(queue);
            receiver.setMessageListener(this);
            connection.start();
            . . .


Receiver: Wait for stop and exit

Next, the program goes into a loop that will exit when the stop variable becomes true. In the loop, the thread sleeps for one second. Once the loop has exited, the Connection is closed and the program terminates.

    . . .
            //Wait for stop
            while (!stop) {
                Thread.sleep(1000);
            }

            //Exit
            System.out.println("Exiting...");
            connection.close();
            System.out.println("Goodbye!");

        } catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    . . .


Receiver: onMessage(Message) method

The presence of the Receiver class's onMessage(Message) method is required because Receiver implements the MessageListener interface.

When a message is received, this method is called with the Message passed as the parameter.

In our implementation, we get the text content of the message and print it to System.out. We then check to see if the message equals stop, and if it does, the stop variable is set to true; this allows the loop in the receive() method to terminate.

    . . .
    public void onMessage(Message message) {

        try {
            String msgText = ((TextMessage) message).getText();
            System.out.println(msgText);
            if ("stop".equals(msgText))
                stop = true;
        } catch (JMSException e) {
            e.printStackTrace();
            stop = true;
        }
    }
}


Running the programs

As indicated in the Getting started , you need the javax.naming and javax.jms packages to compile the Sender and Receiver programs.

Before you run the programs, you need to use the administration tool supplied by your JMS provider to create the ConnectionFactory and Destination administered objects and place them in the JNDI namespace.

You also need to make sure that the provider's JMS implementation classes are in your classpath.

You can then run both of these programs at the same time, supplying the same JNDI names for the ConnectionFactory and Destination, and send messages from the Sender to the Receiver.

5 of 13 | Previous | Next

Comments



Help: Update or add to My dW interests

What's this?

This little timesaver lets you update your My developerWorks profile with just one click! The general subject of this content (AIX and UNIX, Information Management, Lotus, Rational, Tivoli, WebSphere, Java, Linux, Open source, SOA and Web services, Web development, or XML) will be added to the interests section of your profile, if it's not there already. You only need to be logged in to My developerWorks.

And what's the point of adding your interests to your profile? That's how you find other users with the same interests as yours, and see what they're reading and contributing to the community. Your interests also help us recommend relevant developerWorks content to you.

View your My developerWorks profile

Return from help

Help: Remove from My dW interests

What's this?

Removing this interest does not alter your profile, but rather removes this piece of content from a list of all content for which you've indicated interest. In a future enhancement to My developerWorks, you'll be able to see a record of that content.

View your My developerWorks profile

Return from help

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Java technology
ArticleID=131862
TutorialTitle=Introducing the Java Message Service
publish-date=06082004
author1-email=willyf@us.ibm.com
author1-email-cc=

Tags

Help
Use the search field to find all types of content in My developerWorks with that tag.

Use the slider bar to see more or fewer tags.

Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere).

My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).

Use the search field to find all types of content in My developerWorks with that tag. Popular tags shows the top tags for this particular content zone (for example, Java technology, Linux, WebSphere). My tags shows your tags for this particular content zone (for example, Java technology, Linux, WebSphere).