background image

JMS Message Listeners

<< JMS Message Consumers | JMS Message Selectors >>
<< JMS Message Consumers | JMS Message Selectors >>

JMS Message Listeners

You use the receive method to consume a message synchronously. You can use this method at
any time after you call the start method:
connection.start();
Message m = consumer.receive();
connection.start();
Message m = consumer.receive(1000); // time out after a second
To consume a message asynchronously, you use a message listener, described in the next
section.
JMS 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, you define the actions to be taken when a message arrives.
You register the message listener with a specific MessageConsumer by using the
setMessageListener
method. For example, if you define a class named Listener that
implements the MessageListener interface, you can register the message listener as follows:
Listener myListener = new Listener();
consumer.setMessageListener(myListener);
After you register the message listener, you call the start method on the Connection to begin
message delivery. (If you call start before you register the message listener, you are likely to
miss messages.)
When message delivery begins, the JMS provider automatically calls the message listener's
onMessage
method whenever a message is delivered. The onMessage method takes one
argument of type Message, which your implementation of the method can cast to any of the
other message types (see
"Message Bodies" on page 908
).
A message listener is not specific to a particular destination type. The same listener can obtain
messages from either a queue or a topic, depending on the type of destination for which the
message consumer was created. A message listener does, however, usually expect a specific
message type and format.
Your onMessage method should handle all exceptions. It must not throw checked exceptions,
and throwing a RuntimeException is considered a programming error.
The session used to create the message consumer serializes the execution of all message listeners
registered with the session. At any time, only one of the session's message listeners is running.
In the Java EE platform, a message-driven bean is a special kind of message listener. For details,
see
"Using Message-Driven Beans to Receive Messages Asynchronously" on page 956
.
The JMS API Programming Model
The Java EE 5 Tutorial · September 2007
906