JMS - Quick Guide

The term JMS stands for Java Message Service, a Java API which acts as a interface between applications to create, send, receive and read messages between them. 
Java Message Service is developed by Sun Microsystems as a part of Java Platform Enterprise Edition. The first version of JMS i.e. JMS 1.0.2b was released in June 26, 2001. The stable version of JMS is JMS 2.0 released in May 21, 2013.
JMS is a messaging service which provides reliable and asynchronous communication to implement the messaging system between Java based applications and software components. The JMS API provides set of interfaces to communicate with Java programs and also defines standard messaging protocols to support the Java programming language.
It provides support for messaging applications in J2EE (Java 2 Platform, Enterprise Edition) technology to interact with other applications.
It provides support for messaging applications in J2EE (Java 2 Platform, Enterprise Edition) technology to interact with other applications.
It provides a common interface to communicate with messaging implementations.
It provides a common interface to communicate with messaging implementations.
The application developed with JMS API, can be deployed in any JMS provider software.
The application developed with JMS API, can be deployed in any JMS provider software.
Developers can easily create messaging enterprise applications by quickly learning JMS API.
Developers can easily create messaging enterprise applications by quickly learning JMS API.
It is an asynchronous system, which delivers the messages to a client as they arrive and it does not have to request to receive a message. When the messages are available, they will reach to the client automatically. 
It is an asynchronous system, which delivers the messages to a client as they arrive and it does not have to request to receive a message. When the messages are available, they will reach to the client automatically. 
It is a determined messaging service in which it facilitates that a message will be delivered to destination system only once, so that you can create reliable applications easily.
It is a determined messaging service in which it facilitates that a message will be delivered to destination system only once, so that you can create reliable applications easily.
It allows exchanging and using information between other Java Platform languages such as Scala and Groovy.
It allows exchanging and using information between other Java Platform languages such as Scala and Groovy.
If you send header and other information along with the message content, then it leads to increase in network traffic as the total amount of information becomes larger than the message content itself.
If you send header and other information along with the message content, then it leads to increase in network traffic as the total amount of information becomes larger than the message content itself.
If you forward the message to receivers via server, then the communication will get slower than direct communication.
If you forward the message to receivers via server, then the communication will get slower than direct communication.
The Java Messaging Service is an API used in J2EE technology for exchanging information between two separate and independent network entities (group of hosts). It also provides reliable, asynchronous communication with other applications.
Before beginning with JMS API, we will see what is messaging system?
Message is an information that communicates between different components in the same system or different systems. Message can be a text, XML document, and JSON data etc which take place either in synchronous or asynchronous manner. A client can create, send, receive and read the messages by using the messaging agent. Messaging is quite different from electronic mail (e-mail). E-mail communicates between people whereas Messaging system communicates between software applications or software components.
The Java Message Service API provides a set of interfaces for applications to create, send, receive, and read messages. It also exchanges information between different systems. It provides reliable and asynchronous communication to implement the messaging systems in Java-based applications. It maximizes the portability of the JMS applications in the messaging domain.
If you develop the messaging system by using JMS API, then you can deploy the same application in any JMS Provider software.
JMS application contains following elements −
JMS clients − JMS clients use JMS API to send and receive messages.
JMS clients − JMS clients use JMS API to send and receive messages.
Messages − It includes the data which will be exchanged between JMS clients.
Messages − It includes the data which will be exchanged between JMS clients.
JMS provider − It is a message oriented middleware software, that provides UI components to administrate the JMS application.
JMS provider − It is a message oriented middleware software, that provides UI components to administrate the JMS application.
JMS Sender − It is commonly known as  JMS Producer or Publisher, which is used to send messages to destination system.
JMS Sender − It is commonly known as  JMS Producer or Publisher, which is used to send messages to destination system.
JMS Receiver − It is generally known as  JMS Consumer or Subscriber, which is used to receive messages to the destination system.
JMS Receiver − It is generally known as  JMS Consumer or Subscriber, which is used to receive messages to the destination system.
JMS provides two types of messaging domains −
Point-to-Point Messaging Domain
Publish/Subscribe Messaging Domain
In this type, it includes a sender, a receiver and a queue in which one message will be sent to only one receiver. Each message will communicate to a specific queue. The queue will carry the message until receiver is ready. 
In this type, it includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies. They can publish or subscribe to the topic, which manages the delivery of messages.
We will look on point-to-point and publish/Subscribe approaches in the upcoming chapters.
The following table shows available JMS providers −
In the previous chapters, we have discussed about overview of JMS API. Now we will see how to setup the development environment   for executing JMS examples. We need to use JMS provider to run JMS API in the applications. Here, we are using OpenJMS service provider for running examples.
You need to have JDK and Eclipse to configure the OpenJMS provider. Download the Java EE (Enterprise Edition) from this link and Eclipse IDE can be downloaded from here.
Step 1 − Download the OpenJMS archive from here. 
Step 2 − Click on the highlighted link and extract the openjms-0.7.7-beta-1.zip to C drive.
Step 3 − Confirm the JAVA_HOME environment variable is set properly. Go to System Properties and click on the Environment Variables. Edit the User Variable and check for the JAVA_HOME variable.
Step 4 − Now open the command prompt and navigate to the extracted folder. Go to the bin folder and type startup as shown in the image below.
Step 5 − Next, it will open the OpenJMS window, which shows the ports for accepting connections. 
The above image indicates that OpenJMS server is started.
JMS architecture is designed by Sun Microsystems as a part of Java Platform Enterprise Edition, which makes Java Message Service (JMS) to develop business applications asynchronously and  provides support for wide range of enterprise messaging products. JMS supports two types of messaging domains; one is point-to-point messaging domain and another one is publish-subscribe messaging domain. We will be studying about these topics in the upcoming chapters.
The below diagram depicts architecture of JMS API −
JMS API uses an administered tool to bind the administered objects such as connection factories and destinations, to the  Java Naming and Directory Interface (JNDI) name space. JNDI is a Java API used to find the data with particular name. A JMS client looks for the administered objects in the JNDI namespace to create logical connection with these objects and destination by using the service provider.
JMS API includes following components −
JMS Provider − It is message oriented middleware software that provides JMS interfaces to administrate JMS application and also defines messaging features to the clients.
JMS Provider − It is message oriented middleware software that provides JMS interfaces to administrate JMS application and also defines messaging features to the clients.
JMS Clients − JMS clients use JMS API to send and receive messages.
JMS Clients − JMS clients use JMS API to send and receive messages.
Messages − It communicates with clients and exchanges the data between JMS clients to the design of a JMS application.
Messages − It communicates with clients and exchanges the data between JMS clients to the design of a JMS application.
Administered Objects − These are preconfigured objects, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider.
Administered Objects − These are preconfigured objects, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider.
The point-to-point message approach includes a sender, a receiver and a queue; in which one message will be sent to only one receiver. Each message will communicate to a specific queue and the same queue will carry the message until receiver is ready. 
The parts (sender, receiver and queue) of this approach will specify that, each message communicates with a specific queue. The sending client will forward the message to queue and receiver client then extracts the message from the queue. A queue will keep all the messages, until they are consumed or expired.
The point-to-point message approach has following features −
It contains one client for each message.
It contains one client for each message.
The sender and receiver of message will not have any timing dependency.
The sender and receiver of message will not have any timing dependency.
The receiver will send an acknowledgment, after successfully receiving the message.
The receiver will send an acknowledgment, after successfully receiving the message.
Each message communicates with a specific queue.
Each message communicates with a specific queue.
The publish/subscribe message approach includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies. They can publish or subscribe to the topic, which manages the delivery of messages.
This approach includes multiple publishers and consumers and, a single publisher can include multiple consumers. A message will be delivered to an object called topic (specify the destination), which is responsible for the delivery of a message. The topic will keep the messages and distribute to the present subscribers.
The publish/subscribe message approach has following features −
It contains various subscribers for each message.
It contains various subscribers for each message.
This approach has multiple publishers as well as multiple consumers.
This approach has multiple publishers as well as multiple consumers.
There is timing dependency for publishers and consumers.
There is timing dependency for publishers and consumers.
The JMS API contains following building blocks −
Administered Objects
Connections
Sessions
Message Producers
Message Consumers
Messages
Administered objects are pre-built objects, which can be used by the JMS clients. Administrator uses the Java Naming and Directory Interface (JNDI: It is a Java API, used to find the data with particular name) API namespace to build administered objects. There are two types of administered objects −
Connection Factory − This object provides the connection between JMS client and Service provider.
Connection Factory − This object provides the connection between JMS client and Service provider.
Destination − This object defines the JMS clients, to target the messages and receive messages from the destination.
Destination − This object defines the JMS clients, to target the messages and receive messages from the destination.
Connection uses some JMS providers such as WebSphere, Active MQ, Open MQ etc to create connection with client and defines these provider resources virtually outide the Java Virtual Machine (JVM). It creates connection between client and provider.
It will use the Connection interface along with ConnectionFactory object to create a connection as shown below −
Connection connection = connectionFactory.createConnection();

The connection can be closed by using below line −
connection.close();

It is a light weight JMS object, used for producing and consuming messages. You can create message producers, message consumers, and messages by using sessions.
You can create a session by using Connection object and Session interface as shown below −
//The AUTO_ACKNOWLEDGE field automatically gives the client's receipt messages, when they have been received successfully
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

The message producer is generated by a session, which sends messages to the destination by implementing MessageProducer interface. You can establish a MessageProducer for the destination or queue object as shown below −
MessageProducer producer = session.createProducer(destination);
MessageProducer producer = session.createProducer(queue);

Use the send() method to send the messages after creating message producer.
producer.send(message);

The message consumer is generated by a session, which receives messages from the destination by implementing the MessageConsumer interface. You can establish a MessageConsumer for the destination or queue object as shown below −
MessageConsumer producer = session.createConsumer(destination);
MessageConsumer producer = session.createConsumer(queue);

JMS Messages includes the data, which will be exchanged between JMS clients to the design of a JMS application. Messages are highly flexible, that create messages with the matching formats. For more information, refer this chapter.
JMS message communicates with JMS clients by using three JMS components −
Message Header
Message Properties
Message Body
The JMS message header includes following fields, which are used by clients and providers to indicate and send messages.
JMSDestination
JMSDeliveryMode
JMSTimestamp
JMSMessageID
JMSReplyTo
JMSCorrelationID
JMSReplyTo
JMSRedelivered
JMSType
JMSExpiration
JMSPriority
Properties can be created and set for the messages by using the custom name value pairs. The message properties are used with other messaging systems, to create message selectors and for supporting filtering messages.
The JMS API provides following message body formats, which are used to send and receive the information in various forms −
Text message − It defines the text message by using the javax.jms.TextMessage interface.
Text message − It defines the text message by using the javax.jms.TextMessage interface.
Object message − It defines the Java object by using the javax.jms.ObjectMessage interface.
Object message − It defines the Java object by using the javax.jms.ObjectMessage interface.
Bytes message − It specifies the binary data by using the javax.jms.BytesMessage interface.
Bytes message − It specifies the binary data by using the javax.jms.BytesMessage interface.
Stream message − It specifies the Java's primitive values (such as int, char, float etc) by using the javax.jms.StreamMessage interface.
Stream message − It specifies the Java's primitive values (such as int, char, float etc) by using the javax.jms.StreamMessage interface.
Map message − It specifies the key/value pair by using the javax.jms.MapMessage interface.
Map message − It specifies the key/value pair by using the javax.jms.MapMessage interface.
An enterprise messaging system is frequently called as message oriented middleware (MOM) to combine the applications in a flexible way. The MOM acts as mediator between two applications to communicate with each other.
The messaging flexibility can be explained as shown in the figure below −
In the above figure, you can see that, Application One communicates with Application Two by using Enterprise Messaging System and sends message via Application Programming Interface (API). The Enterprise Messaging System sends the message to Application Two which is present on different system by handling the network communications. The messaging system will forward the message to Application Two, if there is a network connection; otherwise it will store the message until the connection becomes available, and then send it to Application Two.
It is a process of connecting the components of a system by reducing the inter dependencies between them. Loose Coupling increases the flexibility of system and makes the application more maintainable and stable.
JMS is a standard Java interface for enterprise messaging system and it is widely used technology for loosely coupled systems, which are executed in Java. 
The publish/subscribe message approach includes multiple publishers and multiple consumers in which one message will be sent to all clients. Here, both publishers and subscribers are generally unknown and they will have timing dependencies
For more information on publish/subscribe message approach, refer this chapter.
The JMS API can be used to create, send, receive and read message in the applications and has become integral part of Java EE platform. The Java EE applications use JMS API within EJB (Enterprise Java Beans) and web containers, which apply Java EE platform specification to Java EE components.
EJB is an essential part of a J2EE  (Java 2 Enterprise Edition) platform, which develops and deploy the enterprise applications, by considering robustness, high scalability, and high performance. Web containers are used for the execution of web pages, which run on web servers like Jetty, Tomcat etc.
The following ways describe the use of JMS API in the J2EE application −
These are preconfigured objects in the J2EE application, generated by an administrator to use with JMS clients. There are two types of administered objects; namely destination and connection factory. A destination is an object, that target its messages by JMS clients and receives the messages from the destination. The connection factory is an object, which establishes the connection between JMS client and Service provider. For more information, refer to the Programming Model chapter.
It defines the name of the injected bean in Java EE applications and you can specify the JMS resource as static in an application client component. It can be specified as shown below −
@Resource(lookup = "jms/ConnectionFactory")
private static ConnectionFactory connectionFactory;

@Resource(lookup = "jms/Queue")
private static Queue queue;
In the J2EE application, the JMS API resources contain JMS API connection and session. If you are using JMS API for an enterprise bean instance, then create the resource by using @PostConstruct callback method and close the resource by using @PreDestroy callback method.
The JMS API allows developers to create enterprise applications easily and defines the synchronous and asynchronous, reliable communications between J2EE components and other applications. The enterprise applications can be developed with new message-driven beans for defining business events along with existing business events.
The bean method can send and receive the message by using the container-managed transactions, instead of using local transactions and manipulates the transaction separation with help of EJB container. Keep the occurrence of JMS operations and database access in a single transaction, by sending and receiving the messages in Java Transaction API (JTA) transactions. You don't need to use an annotation to specify the container-managed transactions, because they are default transactions in the Java EE applications.
The message-driven bean is special type of enterprise bean supported by J2EE application, which processes the JMS messages asynchronously in the Java EE applications. The session bean sends and receives the JMS messages synchronously. The messages sent from client's application, enterprise bean, or a web component does not use Java EE technology.
The message-driven bean class contains below features −
This class uses the javax.jms.MessageListener interface to receive asynchronously delivered messages and onMessage method for moving the message to listener.
This class uses the javax.jms.MessageListener interface to receive asynchronously delivered messages and onMessage method for moving the message to listener.
It creates a connection by using @PostConstruct callback method and closes the connection by using @PreDestroy callback method. Generally, this class uses these methods to produce the messages and receive the messages from another destination.
It creates a connection by using @PostConstruct callback method and closes the connection by using @PreDestroy callback method. Generally, this class uses these methods to produce the messages and receive the messages from another destination.