Home > Articles > Programming > Java

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account