Home > Articles > Programming > Java

This chapter is from the book

Message Types

There are five standard JMS message types, and the WebLogic JMS implementation defines an additional XML message type.

JMS Message Types

Table 7.3 lists the JMS message types.

Table 7.3 JMS Message Types

Message Type

Description

StreamMessage

This message type consists of a serialized stream of objects. The objects must be read from the stream in the order they were written.

MapMessage

A message consisting of name/value pairs. Like a hash table, these are unordered, and each name must be unique within the map.

TextMessage

A message type to hold a string.

ObjectMessage

A message that holds a serialized object.

BytesMessage

A raw stream of bytes. Clients who need complete control over the raw message format use this message type.

XMLMessage

The WebLogic JMS implementation extends the TextMessage type with the XMLMessage to provide optimized delivery and selection of XML messages.


Reusing Message Objects

A JMS Message object can be reused for many messages. When a message is sent, the JMS provider copies the associated message data into an internal buffer before the send call returns control to the caller. Once the send call has returned, the sender can reuse the Message object. This enables the producer to avoid the cost of creating a Message object every time a message is sent.

The message consumer receives a Message object from the JMS Server. The JMS specification prohibits the message receiver from modifying the Message object. To the receiver, the Message object is read-only. This enables the WebLogic JMS implementation to be more efficient because it does not have to copy the message before it delivers it to the consumer.

JMS Delivery Modes

JMS allows messages to be either persistent or nonpersistent. When a persistent message is sent, the JMS implementation saves the message to a backing store such as a database or a file store. The JMS Server ensures that the send does not complete until the message has been saved. Because this message is persistent (it's stored in \jms_store\MyJMSFileStoreXXX.dat), it can survive a system crash. JMS also offers nonpersistent messages. Unlike persistent messages, JMS only keeps nonpersistent messages in memory. If a system crash occurs, all nonpersistent messages are lost.

The choice between persistent and nonpersistent messages is a trade-off between reliability and performance. Nonpersistent messages offer higher performance because no disk writes or database updates are performed. However, nonpersistent messages can be lost in a system crash. Applications that require reliability and durable messages should use persistent messages.

Choose nonpersistent messages when messages do not need to survive a server crash. Choose persistent messages when messages must be delivered at least once.

When the server administrator creates a ConnectionFactory, a default delivery mode may be specified. If no delivery mode is specified, the WebLogic JMS implementation defaults to persistent delivery. Any connection created from the ConnectionFactory will use the default delivery mode. The JMS client may override the default delivery mode when a message is sent by explicitly passing a delivery mode. For instance:

msg.setText("Override for this message");
sender.send(
 msg,
DeliveryMode.NON_PERSISTENT,
Message.DEFAULT_PRIORITY,
Message.DEFAULT_TIME_TO_LIVE
   );

Persistent messages require the WebLogic Server administrator to configure a backing store. The WebLogic JMS implementation supports either Java Database Connectivity (JDBC) or file stores. If a persistent store is not configured, only nonpersistent messages may be used. Figure 7–1 illustrates creating a backing store in the file system.

Synchronous vs. Asynchronous Receivers

JMS supports both synchronous and asynchronous message consumers. A synchronous consumer uses the QueueReceiver's or TopicReceiver's receive() method to retrieve the destination's next message. If a message is available, the JMS implementation will return it; otherwise, the client's call waits indefinitely for a message. JMS also offers two variants, receiveNoWait() and receive(long timeout). The receiveNoWait() method returns a message if one is available; otherwise, it returns null. The receive(long timeout) method takes a timeout parameter to specify the maximum amount of time to wait for a message. If a message is available within the timeout, it is returned, but if the timeout expires, null is returned.

Asynchronous message consumers must implement the javax.jms. MessageListener interface, which contains the onMessage(Message) method.

public class AsyncMessageConsumer
 implements javax.jms.MessageListener
{

 ...

 public void onMessage(Message m)
  throws JMSException
 {

  // process message here
 }

}

The asynchronous receiver calls the QueueReceiver or TopicReceiver's setMessageListener method to register itself with JMS.

 receiver.setMessageListener(new AsyncMessageConsumer());

The JMS implementation delivers messages by calling the MessageListener's onMessage method and passing it the new message. The JMS implementation will not deliver another message to this MessageListener instance until the onMessage method returns.

Most JMS applications should use asynchronous message consumers and avoid making synchronous receive calls. A receive call consumes a server thread while it is blocking, but an asynchronous receiver is dispatched to an available thread only when a message is received. Threads are valuable server resources and blocking should be minimized or avoided. If a design requires a synchronous consumer, the receiveNoWait or receive(long timeout) methods should be used instead of blocking, possibly indefinitely, in receive().

Use receive(long timeout) or receiveNoWait for synchronous consumers.

Message Selectors

Many message consumers are only interested in a subset of all delivered messages. JMS provides a standard message selector facility to perform automatic message filtering for message consumers. The message filtering is performed by the JMS implementation before delivering the message to consumers.

A JMS message consumer writes a JMS expression to perform message filtering. This expression is evaluated by the JMS implementation against the JMS message headers and properties. The message filtering never considers the message body. If the JMS expression evaluates to true, the message is delivered to this consumer. When the JMS expression evaluates to false on a queue, the message is skipped, but it still remains in the queue. On a topic, a false selector will ignore the message for this subscriber. If the topic includes multiple subscribers, then the message may be delivered to other subscribers who do not filter it out.

JMS message selectors are string expressions based on SQL-92. The expression must evaluate to a boolean value using a set of standard operators and the message's header and properties. Each message consumer may use a single selector, and the selector must be specified when the consumer is created.

For instance, this selector ensures that messages will only be delivered if the priority is greater than 5.

 receiver = session.createReceiver(messageQueue, 
   "JMSPriority > 5");

Most JMS filtering uses the message properties. This enables the producer to set application-specific values in the message, and then the message filtering can use these properties for filtering.

Durable JMS Subscriptions

In JMS's pub/sub domain, message consumers subscribe to topics. A given topic might have many subscribers. When a message arrives, it will be delivered to all subscribers who do not filter the message. If the subscriber's process terminates or there is a network outage, the consumer will miss messages delivered to the topic. These messages will not be redelivered when the client reconnects. This behavior is desirable for many pub/sub applications. For time-sensitive information, there is no reason to retain the message, and the JMS implementation will have higher performance if it does not need to retain messages for lost clients. However, some applications might have identified clients that need to recover topic messages when they reconnect to the server. JMS provides durable topic subscriptions to allow this behavior. Note that durable subscriptions apply only to JMS topics. JMS queues cannot use durable subscriptions.

When durable topic subscriptions are used, the client must provide a unique identifier. For instance, an application could use a user's login name. This enables the server to identify when a client is reconnecting to the JMS Server so that the JMS implementation can deliver any pending messages. The client can set the ID by either creating a connection factory with an associated ID or by calling the setClientID method on the Connection object. While the JMS specification recommends the ConnectionFactory approach, it requires the server administrator to create a ConnectionFactory for each durable client. This is impractical for large production systems. In reality, most applications should set the connection ID explicitly on the JMS connection. The setClientID method must be called immediately after the connection is obtained. Note that it is the client's responsibility to ensure that the client ID value is unique. In a WebLogic cluster, the JMS implementation cannot always immediately determine that there are multiple clients with a given client ID.

This example code creates the TopicConnection from the JMS ConnectionFactory and then establishes a client ID of 1.

  connection = connectionFactory.createTopicConnection();
  connection.setClientID("1");

The JMS consumer then uses the createDurableSubscriber method to create its subscriber object.

  subscriber = session.createDurableSubscriber(topic, "1");

The subscriber will now be attached to the JMS Server with the client ID of "1". Any pending messages to this topic are delivered to this client.

When a durable subscriber is not connected to the JMS Server, the JMS implementation must save any messages sent to the associated topic. This enables durable clients to return and receive their pending messages, but it also forces the JMS Server to maintain a copy of the message until all durable clients have received the message. JMS provides the unsubscribe method for durable subscribers to delete their subscription. This prevents the server from retaining messages for clients that will never return.

  // unsubscribe the client named "1"
  session.unsubscribe("1");

Using Temporary Destinations

JMS destinations are administered objects created from the WebLogic Server's Administration Console. Destinations are named objects that survive server restarts and may be used by many clients. However, some messaging applications require a lightweight, dynamic destination that is created for temporary use and deleted when the client finishes. JMS includes temporary destinations to address this requirement.

A JMS client creates a temporary destination with QueueSession's createTemporaryQueue() method or TopicSession's createTemporaryTopic() method.

  TemporaryQueue tempQueue = session.createTemporaryQueue();

The TemporaryQueue (and conversely TemporaryTopic) extend the Queue class and add only a delete() method. The delete() method destroys the temporary destination and frees any associated resources. This TemporaryQueue is a system-generated temporary queue. Temporary destinations do not survive server restarts, and clients may not create durable subscribers for temporary topics. Each temporary destination exists within a single JMS connection, and only the encompassing JMS connection creates message consumers for a temporary destination. Because temporary destinations never survive a server restart, there is no reason to persist messages. Any persistent message sent to a temporary destination will be remarked as NON_PERSISTENT by the WebLogic JMS implementation, and it will not survive a server restart.

One common use for temporary destinations is a reply queue. A JMS client sends messages to a JMS Server setting the JMSReplyTo field to the temporary destination name. The message consumer then sends a response to the temporary destination.

Temporary destinations enable JMS applications to dynamically create short-lived destinations. Because temporary destinations do not survive system failures, applications using temporary destinations must be prepared for lost messages.

JMS clients should always call the delete() method when they have finished with a temporary destination. Each temporary destination consumes resources within the WebLogic Server. These resources are reclaimed when the delete() method is called or through garbage collection.

Message Acknowledgment

The JMS Server retains each message until the consumer acknowledges the message. When messages are consumed within a transaction, the acknowledgment is made when the transaction commits. With nontransacted sessions, the receiver specifies an acknowledgment mode when the session is created. The JMS specification defines three standard acknowledgment modes, and the WebLogic JMS implementation adds two additional options.

Table 7.4 lists the JMS acknowledgment modes.

Table 7.4 JMS Acknowledgment Modes

Acknowledgment Mode

Description

AUTO_ACKNOWLEDGE

For synchronous receivers, the message will be automatically acknowledged when the consumer's receive method call returns without throwing an exception. With an asynchronous consumer, the message is acknowledged when the onMessage callback returns.

DUPS_OK_ACKNOWLEDGE

This acknowledgment mode enables JMS to lazily acknowledge message receipt. It is more efficient than AUTO_ACKNOWLEDGE because every message is not acknowledged, but messages may be redelivered if a system crash or network outage occurs.

CLIENT_ACKNOWLEDGE

This acknowledgment mode requires the client to use the javax.jms.Message.acknowledge() method to explicitly acknowledge messages. It is not necessary for the client to acknowledge every message. Instead, a call to acknowledge() will acknowledge the current and any previous messages.

NO_ACKNOWLEDGE

This is a WebLogic JMS acknowledgment mode to indicate that no acknowledgment is required. The JMS implementation does not retain the message after delivering it to the consumer.

MULTICAST_NO_ACKNOWLEDGE

This is a WebLogic JMS acknowledgment mode that delivers JMS messages via IP multicast to topic subscribers. Like NO_ACKNOWLEDGE, the JMS implementation does not retain the message after delivery.


Which Acknowledgment Mode Is Right for Your Application?

NO_ACKNOWLEDGE or MULTICAST_NO_ACKNOWLEDGE should be used by applications where performance outweighs any durability or recoverability requirements. In many applications, messages are created frequently to send out updates such as the latest stock quotes. Because this information is continually being generated, performance is paramount, and if a system crash occurs, there is no reason to recover any lost stock quotes since the quote will be out of date by the time the system has recovered.

AUTO_ACKNOWLEDGE is a simple model because the container handles acknowledgment, but JMS programmers should be aware that messages can be redelivered. If there is a system outage between the time that the receive or onMessage call returns and the JMS Server acknowledges the message, the last message will be redelivered when the system recovers. Consumers who need stronger messaging guarantees should use JMS's transaction facilities, which are discussed in the next section.

DUPS_OK_ACKNOWLEDGE allows higher performance than AUTO_ACKNOWLEDGE at the cost of more redelivered messages after a system failure. If consumers can detect or tolerate redelivered messages, its performance advantages make it preferable to AUTO_ACKNOWLEDGE.

CLIENT_ACKNOWLEDGE gives the receiver complete control over the message acknowledgment. It enables the client to acknowledge a batch of messages with a single operation.

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