JMS

What Is Messaging?

Messaging is a method of communication between software components or applications. A messaging system is a peer-to-peer facility: A messaging client can send messages to, and receive messages from, any other client. Each client connects to a messaging agent that provides facilities for creating, sending, receiving, and reading messages.

What Is the JMS API?

The Java Message Service is a Java API that allows applications to create, send, receive, and read messages.

The JMS API enables communication that is not only loosely coupled but also asynchronous and reliable or synchronous.

What is asynchronous messaging?

A JMS provider can deliver messages to a client as they arrive; a client does not have to request messages in order to receive them.

What is synchronous or reliable messaging?

The JMS API can ensure that a message is delivered once and only once. Lower levels of reliability are available for applications that can afford to miss messages or to receive duplicate messages.

When Can We Use the JMS API?

An enterprise application provider is likely to choose a messaging API over a tightly coupled API, such as Remote Procedure Call (RPC), under the following circumstances.

  • The provider wants the components not to depend on information about other components’ interfaces, so that components can be easily replaced.
  • The provider wants the application to run whether or not all components are up and running simultaneously.
  • The application business model allows a component to send information to another and to continue to operate without receiving an immediate response.

What is point-to-point messaging?

A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.

What is publish/subscribe messaging?

In publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic’s multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.

What are the characteristics of publish/subscribe messaging?

Each message may have multiple consumers.

Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

How does synchronous message consumption happen?

A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.

How does asynchronous message consumption happen?

A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage() method, which acts on the contents of the message.

What are the message types available in JMS?

TextMessage: A java.lang.String object (for example, the contents of an Extensible Markup Language file).

MapMessage: A set of name/value pairs, with names as String objects and values as primitive types in the Java programming language. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined.

BytesMessage: A stream of uninterpreted bytes. This message type is for literally encoding a body to match an existing message format.

StreamMessage: A stream of primitive values in the Java programming language, filled and read sequentially.

ObjectMessage: A Serializable object in the Java programming language.

Message: Nothing. Composed of header fields and properties only. This message type is useful when a message body is not required.

What are administered objects in JMS?

Two parts of a JMS application–destinations and connection factories–are best maintained administratively rather than programmatically.

Connection Factories: A connection factory is the object a client uses to create a connection with a provider. A connection factory encapsulates a set of connection configuration parameters that has been defined by an administrator.

For JMS client program, we need to perform a JNDI API lookup of the connection factory.

Calling the InitialContext() method without any parameter results in a search of the current classpath for a vendor-specific file named jndi.properties.

Destinations: A destination is the object a client uses to specify the target of messages it produces and the source of messages it consumes.

In point-to-point messaging domain, destinations are called queues and in publish/subscribe messaging domain, destinations are called topics.

In addition to looking up a connection factory, we need to look up a destination like queue or topic.

Connections: A connection encapsulates a virtual connection with a JMS provider. A connection could represent an open TCP/IP socket between a client and a provider service daemon. We use a connection to create one or more sessions.

Like connection factories, connections come in three forms, implementing either the QueueConnection or the TopicConnection interface or Connection interface for both Queue or Topic.

Sessions: A session is a single-threaded context for producing and consuming messages. We use sessions to create message producers, message consumers, and messages.

A session provides a transactional context with which to group a set of sends and receives into an atomic unit of work.

Sessions come in three forms, implementing either the QueueSession, the TopicSession or the Session interface.

Message Producers: A message producer is an object created by a session and is used for sending messages to a destination. The point-to-point form of a message producer implements the QueueSender interface. The publish/subscribe form implements the TopicPublisher interface.

For example, we use a QueueSession to create a sender for the queue, and we use a TopicSession to create a publisher for the topic.

Message Consumers: A message consumer is an object created by a session and is used for receiving messages sent to a destination. A message consumer allows a JMS client to register interest in a destination with a JMS provider. The JMS provider manages the delivery of messages from a destination to the registered consumers of the destination.

The point-to-point form of message consumer implements the QueueReceiver interface. The publish/subscribe form implements the TopicSubscriber interface.

For example, we use a QueueSession to create a receiver for the queue, and a TopicSession to create a subscriber for the topic.

Message Listeners: A message listener is an object that acts as an asynchronous event handler for messages. This object implements the MessageListener interface, which contains one method, onMessage(). In the onMessage() method, we define the actions to be taken when a message arrives.

We register the message listener with a specific QueueReceiver or TopicSubscriber by using the setMessageListener() method.

What are the acknowledgement options available in JMS?

If application does not use transactions, it can use one of these acknowledgement modes: auto, duplicates okay or client.

Acknowledgement options:

Auto mode (AUTO_ACKNOWLEDGE): specifies that the session is to automatically acknowledge consumer receipt of messages when message processing has finished. This mode guarantees message delivery only once.

Duplicates okay mode (DUPS_OK_ACKNOWLEDGE): specifies that the session is to lazily acknowledge the delivery of messages to the consumer. “Lazy” means that the consumer can delay acknowledgement of messages to the server until a convenient time; meanwhile the server might redeliver messages. This mode reduces session overhead. However, should JMS fail, the consumer may receive duplicate messages. Under rare circumstances, if JMS fails, the consumer may receive duplicate messages. This mode enables at-least-once message delivery guarantee.

Client mode (CLIENT_ACKNOWLEDGE): specifies that the consumer is to acknowledge all messages that have been delivered so far by the session. Therefore the messages sent or received from the session are not acknowledged automatically and the application must acknowledge the message receipt.

What are the transaction options available in JMS?

If application uses transactions, it can choose from these transaction options: transacted session, MDB (Message Driven Bean) with container-managed transaction demarcation (CMTD), and MDB with bean-managed transaction demarcation (BMTD).

Transaction options:

Transacted session: An application can participate in a transaction by creating a transacted session (also known as local transaction). The application completely controls the message delivery by either committing or rolling back the session.

Message-driven beans with CMTD: An MDB can participate in a container transaction by specifying CMTD in the XML deployment descriptor. The transaction commits upon successful message processing or the application can explicitly roll it back.

Message-driven beans with BMTD: An MDB can choose not to participate in a container transaction by specifying BMTD in the XML deployment descriptor. The MDB programmer has to design and write code for programmatic transactions.

What is QueueBrowser?

QueueBrowser tells how many messages are currently available in a Queue.

What is the difference between Queue and Topic?

A topic is typically used for one to many messaging, while queue is used for one-to-one messaging. Topic supports publish/subscribe messaging domain where queue supports point-to-point messaging domain.

What is the role of the JMS server? Why is it necessary?

The server or also called message broker functions as an intermediary.

For example, a distributed component wants to send financial stock information to one or more remotely located distributed components. Rather than having to know the exact clients to which it sends messages containing stock information, it can establish either a message queue or a message topic area (depending on the message-passing scheme, point-to-point or publish/subscribe) with the JMS server and post the stock information with the server or broker, which then distributes the messages to the appropriately registered receiving clients.

Also, without this intermediary or broker, the sending client would have the burden of monitoring whether or not the receiving client is currently connected, whether or not a network failure occurred during the send operation, and so on. The server or broker plays an important role in transparently handling many network-related issues, including reliable message delivery, which can require transaction processing and/or persistent message storage.

Does JMS provide load balancing, fault tolerance, scalability etc.?

The JMS specification does not provide such features; hence, vendors are free to implement their own support, and many vendors already provide these services.

How does JMS compare to peer-to-peer distributed computing?

The term peer-to-peer is used in a variety of ways in distributed and network computing. One usage, at the application level, is to describe a distributed application scenario in with each distributed component potentially interacts with every other distributed component and maintains a network reference (access) to each component (using any of several mechanisms to do so, for example, via Enterprise JavaBeans and EJB servers resident on each network host, via simple RMI-based communication among applications, and so on).

With JMS, distributed components interact with the JMS broker via destinations (topics and queues), which then disseminates messages to the registered clients; thus, distributed components do not have to know (and manage) each other’s’ network locations. As for the JMS middleware, it can use (behind the scenes) any of several network topologies, for example, bus, ring, hierarchical, fully connected (peer-to-peer), star (hub-and-spoke), or others, including hybrids.

Messaging systems are peer-to-peer distributed systems in the sense that, at least potentially, every (registered) client can communicate with every other (registered) client.

What is the difference between durable and persistent message?

A durable message is applicable only to publish/subscribe messaging domain and the persistent message is applicable to both point-to-point and publish/subscribe messaging domain.

A durable message is a message where the broker will hold on to a message if the subscriber is temporarily unavailable. So the durability is defined between a topic subscriber and the JMS broker. For this to happen subscribers need to register themselves with a unique client id.

A persistent message is a message that defines the relationship between a message producer and the JMS broker. This can be established for both point-to-point and publish/subscribe messaging domain. This has to do with the guaranteed only once delivery of the message by persisting the message after it has been received from the message producer.

Can we send e-mail messages using JMS?

JMS has no inherent support for email operations.

What is the difference between JMS and RPC (Remote Procedure Call)?

The basic difference between JMS and RPC lies in the way they communicate.

JMS uses asynchronous messaging type while, RPC creates synchronous messaging type. The method invoker in RPC, waits for the method to finish execution and return the control back to the invoker.

In JMS the message sender just sends the message to the destination and continues its own processing.

In JMS there is no need for the destination object to be available online while sending a message from the client to the server.

How does encryption happen on message through JMS?

The encryption and decryption of the messages is handled by JMS provider and it is not related to JMS specifications. Sonic MQ by Progress Software is a leading JMS provider and they do encryption through encryption mechanisms called Quality of Protection.

How to create temporary Destinations?

The JMS API also enables you to create temporary destinations such as TemporaryQueue and TemporaryTopic that last only for the duration of the connection in which they are created. You create these destinations dynamically using the Session.createTemporaryQueue() and the Session.createTemporaryTopic() methods.

The only message consumers that can consume from a temporary destination are those created by the same connection that created the destination. Any message producer can send to the temporary destination. If you close the connection that a temporary destination belongs to, the destination ceases to exist and its contents are lost.

You can use temporary destinations to implement a simple request/reply mechanism. If you create a temporary destination and specify it as the value of the JMSReplyTo message header field when you send a message, then the consumer of the message can use the value of the JMSReplyTo field as the destination to which it sends a reply. The consumer can also reference the original request by setting the JMSCorrelationID header field of the reply message to the value of the JMSMessageID header field of the request. For example, an onMessage() method can create a session so that it can send a reply to the message it receives.

Can a connection be re-established if a failure occurs at one side of the communication link (i.e. an application that’s sending/receiving messages) and is restarted?

When the network connection between the client and server is lost then JMS provider must try to re-establish the connection. If the JMS provider cannot reconnect, the provider must notify the client using ExceptionListener interface. The ExceptionListener is bound to the connection.

The ExceptionListener interface is given below:

public interface ExceptionListener{
    void onException(JMSException exception);
}

If a JMS provider detects a serious problem with a connection, it informs the connection’s registered ExceptionListener. It does this by calling the listener’s onException() method, passing it a JMSException object describing the problem.

An exception listener allows a client to be notified of a problem asynchronously. Some connections only consume messages, so they would have no other way to learn their connection has failed.

A connection serializes execution of its ExceptionListener.

A JMS provider should attempt to resolve connection problems itself before it notifies the client of them.

What are decentralized and centralized MOM(Message Oriented Middleware)?

Centralized MOM means centralized messaging. JMS uses centralized messaging, where every application/client talks to a centralized messaging broker or server, even for point-to-point communication. In decentralized MOM, the clients communicate to each other directly.

What does header of a message contain?

The header of a message contains message identification and routing information.

This includes, but is not limited to:

  • JMSDestination
  • JMSDeliveryMode
  • JMSMessageID
  • JMSTimeStamp
  • JMSExpiration
  • JMSReplyTO
  • JMSCorrelationID
  • JMSType
  • JMSRedelivered

What is durable subscription?

A durable subscription on a JMS topic enables a subscriber to receive a copy of all messages published to that topic, even after periods of time when the subscriber is not connected to the server.

Each durable subscription is given a unique identifier called clientId. The client identifier (clientId) is used to associate a connection and its objects with the messages maintained for applications.

The subscription name (subName) is also used to uniquely identify a durable subscription within a given client identifier.

Can we send message from one provider to another provider using JMS?

The JMS specification does not have such feature that one JMS provider be able to send messages directly to another provider.

What is the advantage of persistent message delivery compared to non-persistent message delivery?

If the JMS server experiences a failure, for example, a power outage, any message that it is holding in primary storage potentially could be lost. With persistent storage, the JMS server logs every message to secondary storage, i.e., disk. The logged message is removed from secondary storage only after it has been successfully delivered to all consumers.

How to hold messages in JMS Message Queue if there are any error after consuming message?

For this situation you should create a session like this:

Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);

When you try to deliver the message to your third party app:

If third party app is working you should acknowledge the message using acknowledge() method.

If third party app is down you should not acknowledge it, this way the JMS provider will be able to redeliver it, and the message will not be lost.