Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

The JMS Interfaces

The JMS API is provided through the main package javax.jms. This API allows an application to create the necessary objects for both the PTP and Pub/Sub models. Different classes and interfaces are required depending on which message model your application needs to implement. The following sections describe the necessary classes and interfaces and provide more detail for each.


Remember that the JMS APIs define the set of interfaces. The vendor that provides the implementation must provide concrete classes for these interfaces. For example, when you create a Topic, the vendor is providing a Topic concrete class that implements the JMS Topic interface. As long as you have the vendor's classes in your classpath, most of this is transparent to the developer.


A javax.jms.ConnectionFactory is a factory that provides connections for clients in a JMS application. It's usually configured by an administrator and is given a name and then registered with the naming service. The QueueConnectionFactory and the TopicConnectionFactory interfaces extend the ConnectionFactory interface to provide a unique factory for Queue and Topic messaging models, respectively. When a client needs to get a connection to send or receive a JMS message, the first step is to locate the ConnectionFactory and acquire a javax.jms.Connection.


A javax.jms.Connection represents an open channel to the messaging service. This connection is then used to create a javax.jms.Session that can be used for this client. In some cases, a vendor may use a single instance of the connection and multiplex all JMS communication from the client to the messaging system over this single connection. This is done because creating and maintaining many connections is very resource intensive. The underlying implementation will take care of the details of multiplexing the requests. Connections normally are thread-safe and support multiple clients accessing the connection at the same time.

By default, a connection is created in what is known as the stopped mode. The client must call the start method before delivering or receiving messages. Messages can be created while the connection is stopped, but they will not be delivered and/or received until the connection is started.

To create a connection for a Queue, you can use either of these two methods on the QueueConnectionFactory class:

QueueConnection createQueueConnection() throws JMSException;
QueueConnection createQueueConnection(String username, 
           String password) throws JMSException;

The second method creates a connection with a specific user identity.

To create a connection for a topic, you can use either of these two methods on the TopicConnectionFactory class:

public TopicConnection createTopicConnection() throws JMSException;

public TopicConnection createTopicConnection(String username, String password)
 throws JMSException;


A javax.jms.Session defines a serial order for producing and consuming messages. A JMS session, along with its producers and consumers, should be accessed by only one thread at a time. Although a JMS session can be used to create producers and consumers, if the same application needs to do both, you should use separate sessions for each. The Session interface is extended by the javax.jms.QueueSession and the javax.jms.TopicSession interfaces to provide different functionality depending on the messaging model.

The following method signatures can be used to create a QueueSession and a TopicSession from its respective connection:

public QueueSession createQueueSession(boolean transacted, int acknowledgeMode)
 throws JMSException;
public TopicSession createTopicSession(boolean transacted, int acknowledgeMode)
 throws JMSException

JMS sessions can be transacted or non-transacted. This means that one or more messages produced or consumed can be combined into a single unit of work. If the transaction is successful, all the messages created will be sent. A transaction is committed by calling the commit method on the session. You can roll back the transaction similarly by calling the rollback method. Any locks held will also be released when the transaction is committed or rolled back.

With non-transacted sessions, you must provide an acknowledge mode when calling one of the create session methods. Table 10.3 lists the possible acknowledgement modes that can be used.

Table 10.3 Non-Transacted Session Acknowledge Modes

Acknowledge Mode



The session acknowledges after the receiving application has finished processing the message.


The session acknowledges all messages received when the ACKNOWLEDGE method is called on a message received.


This is similar to the AUTO_ACKNOWLEDGE mode, except that duplicate messages can be received. This should be used only by applications that can deal with duplicate messages. This mode limits the work the session has to do to prevent duplicates.


With transacted sessions, all messages that are sent or received when a transaction is committed are acknowledged at that time. The acknowledge mode is ignored when using transacted sessions.

You determine whether a session is transacted by setting the transacted flag when creating the session. If you set it to true, the session will use a transaction. For a nontransacted session, set the value to false. The following code fragment shows how to create a transacted QueueSession:

QueueSession queueSession = null;
try {
 queueSession = createQueueSession(true, Session.AUTO_ACKNOWLEDGE );
} catch ( JMSException ex ) {


A javax.jms.Destination represents a place where you send JMS messages to or receive them from. In one sense it is like an address, in that it is named. The JMS specification does not describe specifically how a JMS vendor must handle a destination address. The vendor-specific format is encapsulated in the Destination object. The destination typically lives on a server that is remote to the clients.

JMS provides two types of destinations, javax.jms.Queue and the javax.jms.Topic. There also are temporary versions of each that are alive only for the duration of the connection. These temporary destinations can be used only by the connection that created it. Typically, a destination is set up by an administrator and is long-lived; that is, it lives longer than any one connection. The destination normally is added to the JNDI namespace, and a client locates the destination using the name it was given during configuration. The following code fragments show how a destination is found using JNDI. This code fragment is assuming that an InitialContext has already been created.

Queue myQueue = null;
try {
 myQueue = (Queue) context.lookup("AuctionNotificationQueue");
} catch( Exception ex ) {

As stated earlier in this chapter, a queue implements the Point-to-Point message model, whereas the topic provides the Pub/Sub message model. The remote references on the client are only handles to the objects on the server. The destination provides no functionality itself but provides a façade for the object on the server. To perform any real work, a message producer or consumer must be created using the destination.

A destination is also given a name that is different from the JNDI name it is given in the JNDI namespace. This name can be used to refer to various life-cycle operations. Don't confuse the JNDI name with the JMS name of the destination. They are used for different reasons.

You typically give the destination its JMS name when you create it.


You might be a little confused about the destination at this point. The destination actually is created by the JMS service or the EJB server when it starts. When you use one of the createQueue or createTopic methods, you really are just creating a reference to a destination on the server. The name that you give it in these create methods is a name that is unique and is used throughout your application.

To later retrieve the name of a destination, you can use one of these two methods, depending on the destination type:

public String getQueueName() throws JMSException;
public String getTopicName() throws JMSException;

MessageProducer and MessageConsumer

As you learned earlier in the section "Components of the JMS Architecture," message producers send messages to a destination and message consumers receive messages from a destination. In the case of JMS, a destination is either a queue or topic. The message producer and consumer are decoupled from one another. A producer will send messages to a destination regardless of whether or not a consumer is there to receive it. A message producer is provided by the javax.jms.MessageProducer interface, and the message consumer is provided by the javax.jms.MessageConsumer interface.

When building a JMS application using the PTP message model, you create a javax.jms.QueueSender and a javax.jms.QueueReceiver. If you were using the Pub/Sub model, you would use the javax.jms.TopicPublisher and the javax.jms.TopicSubscriber interfaces. You can use the associated Session object to create the specific type of producer or consumer depending on the messaging model chosen.

If there are multiple receivers for a queue, the JMS specification does not indicate which receiver will receive a message, but that only one receiver at most will get the message. When using a topic, the messages normally will be sent to every active subscriber.

The same connection can be used to publish and subscribe to a topic. If a publisher is also a subscriber, the publisher will receive a copy of its own messages sent to the destination. This is true only for the Pub/Sub model. This behavior can be modified so that a publisher will not receive its own messages published by setting the noLocal attribute to true when creating the producer or consumer. This will prevent the client from receiving a copy of the message that it has sent to the destination.


The javax.jms.Message interface is the root interface for all JMS messages. It encapsulates all the information being exchanged between applications. There are five types of JMS messages; Table 10.4 summarizes each type.

Table 10.4 JMS Message Types




Used to send a message containing a stream of uninterpreted bytes.


Used to send a set of name-value pairs where names are strings and values are Java primitive types.


Used to send a message that contains a serializable Java object. Only serializable Java objects can be used.


Used to send a stream of Java primitives. It is filled and read sequentially. Its methods are based largely on those found in java.io.DataInputStream and java.io.DataOutputStream.


Used to send a message containing a java.lang.String. This could even be an XML that has been serialized from a StringBuffer.

  • + Share This
  • 🔖 Save To Your Account