Sending and Receiving Messages

Start course
1h 24m

This course covers the Java Message Service (JMS) API and its main concepts. Finally, we will look through example questions.

Learning Objectives

  • Understand the fundamentals of the JMS API and messaging
  • Learn about writing message producers and consumers
  • Learn about reliability mechanisms
  • Learn how to write message-driven beans

Intended Audience

This course is intended for anyone who already has basic knowledge of Java and now wants to learn about Java Enterprise Edition.


Basic knowledge of Java programming.


Hello there. In this lesson, we'll talk about sending and receiving messages in JMS concept. So let's start. Now let's take a look at a simple example to get an idea of how to use the classic JMS API to send and receive a message. JMS employs producers, consumers and destinations. The producer sends a message to the destination where the consumer is waiting for the message to arrive. Destinations can be two kinds; queues for point to point communication and topics for publish- subscribe communication. Here this code represents a producer class that has a main method only. In this method, the first thing that occurs is that a JNDI context is instantiated and is used to obtain a connection factory and a destination. Connection factories and destinations queues and topics are called administered objects.

They have to be created and declared in the message provider. In our case, open mq in glass fish. They both have a JNDI name and need to be looked up in the JNDI tree. When the two administered objects are obtained, the producer class uses the connection factory to create a connection from which a session is obtained. With this session, a message producer in the message are created on the destination queue, session.createproducerqueue. The producer then sends this message of type text. Note that this main class catches the JNDI naming exception as well as the checked JMSException. Fortunately, once you've written this code to send a message, the code to receive it looks almost the same.

In fact, the first lines of the consumer class in code snippet are exactly the same. Create a JNDI context, look up for the connection factory and the destination and then connect. The only differences are that a message consumer is used instead of a message producer, and that the receiver enters an infinite loop to listen to the queue. You'll later see that this loop can be avoided by using the more standard message listener. When the message arrives, it's consumed and the content is displayed. As you can see the code is quite verbose and low level. You need several artifacts to be able to produce or consume a message; connectionFactory connection session. On top of that, you also need to deal with the JMSException, which is a checked exception. JMSException has several sub classes.

This API was created with JMS 1.1 in 2002 and was not changed until JMS 2.0. JMS 2.0 introduces a new simplified API, which consists mainly of three new interfaces, JMSContext, JMSProducer and JMSConsumer. These interfaces rely internally on the connection factory and other classic APIs, but leave the boilerplate code aside. Thanks to the new JMS Runtime exception, which is an unchecked exception, the code to send or receive a message is now much easier to write and read. Here, this figure shows a simplified class diagram of this new API. Note that the legacy classic and simplified APIs are all under the Javax.JMS package. The simplified API provides the same messaging functionality as the classic API but requires fewer interfaces and is simpler to use.

These main interfaces are; JMS Context. Active connection to a JMS provider and a single threaded context for sending and receiving messages. JMS Producer. Object created by a JMS Context that is used for sending messages to a queue or topic. JMS Consumer. Object created by a JMS Context that is used for receiving messages sent to a queue or topic. The JMS Context is the main interface in the simplified JMS API introduced by JMS 2.0. It combines the functionality of two separate objects from the JMS 1.1 classic API, a connection, the physical link to the JMS Provider and a session, a single threaded context for sending and receiving messages. A JMS Context may be created by the application by calling one of the several createContext methods on a connection factory and then closed. Alternatively, if the application is running in a container, EJB or web, the JMS Context can be injected using the @Inject annotation. When an application needs to send messages, it uses the createProducer method to create A JMS Producer, which provides methods to configure and send messages.

Messages may be either sent synchronously or asynchronously. To receive messages, an application can use one of several createConsumer methods to create a JMS Consumer. This table shows us a subset of the JMS Context API. void start(). Starts or restarts delivery of incoming messages. void stop(). Temporarily stops the delivery of incoming messages. void close(). Closes the JMS Context. void commit(). Commits all messages done in this transaction and releases any locks currently held. void rollback(). Rolls back any messages done in this transaction and releases any locks currently held. BytesMessage create BytesMessage(): Creates a byte message object. MapMessage createMapMessage(): Creates a map message object. Message createMessage(): Creates a message object. A JMS Producer is used to send messages on behalf of a JMS Context. It provides various send methods to send a message to a specified destination. An instance of JMS Producer is created by calling the createProducer method on a JMS Context.

It also provides methods to allow send options, message properties and message headers to be specified prior to sending the message. get/set[Type]Property: Sets and returns a message property where 'type' is the type of the property and can be boolean, byte, double, float int, long, object, short, string. JMSProducer clearProperties(): Clears any message property sent. Set<String> getPropertyNames(): Returns an unmodifiable set view of the names of all the message properties that have been set. boolean propertyExists(String name). Indicates whether a message property with the specified name has been set. get/set[Message Header]. Sets and returns a message header where message header can be delivery delay, delivery mode, JMS correlation ID, JMS reply to, JMS type, priority, time to live. JMSProducer send(Destination destination, Message message). Sends a message to the specified destination using any send options, message properties and message headers that have been defined. JMS Producer send (Destination destination, String body). Sends a text message with a specified body to the specified destination.

A JMS Consumer is used to receive messages from a queue or topic. It's created with one of the create consumer methods. on a JMS Context by passing a queue or a topic. As you will later see, a JMS Consumer can be created with a message selector so it can restrict messages delivered. A client may receive a message synchronously or asynchronously as they arrive. For asynchronous delivery, a client can register a messageListener object with a JMS Consumer. As messages arrive, the provider delivers them by calling the message listeners on message method. This table shows us a subset of the JMS Consumer API. void close(). Closes the JMS Consumer. Message receive(). Receives the next message produced. Message receive (long timeout). Receives the next message that arrives within the specified time out interval. <T> <T> T receiveBody(Class T c).

Receives the next message produced and returns its body as an object to the specified type. Message receiveNowait(). Receives the next message if one is immediately available. void setMessageListener (MessageListener listener). Sets the message listener. MessageListener getMessageListener(). Gets the message listener. String getMessageSelector(). Gets the message selector expression. So that's it. Hope to see you in our next lesson. Have a nice day.


About the Author
Learning Paths

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics