Home > Articles > Programming > Java

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.

NOTE

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.

ConnectionFactory

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.

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;

Session

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

Description

AUTO_ACKNOWLEDGE

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

CLIENT_ACKNOWLEDGE

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

DUPS_OK_ACKNOWLEDGE

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.


NOTE

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 ) {
 ex.printStackTrace();
}

Destination

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 ) {
 ex.printStackTrace();
}

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.

NOTE

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.

Message

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

Name

Description

BytesMessage

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

MapMessage

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

ObjectMessage

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

StreamMessage

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.

TextMessage

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


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