17

I am new to JMS. As far as I understood Consumers are capable of picking messages from queue/topic. So why do you need a MessageListener because Consumers will know when they have picked up messages? What is the practical use of such a MessageListener?

Edit:From the Javadoc of MessageListener:

A MessageListener object is used to receive asynchronously delivered messages.

Each session must insure that it passes messages serially to the listener. This means that a listener assigned to one or more consumers of the same session can assume that the onMessage method is not called with the next message until the session has completed the last call.

So I am confused between the usage of the terms asynchronously and serially together. How do these two terms relate in describing the feature of MessageListener?

Geek
  • 26,489
  • 43
  • 149
  • 227

3 Answers3

24

The difference is that MessageConsumer is used to receive messages synchronously:

MessageConsumer mc = s.createConsumer(queue);
Message msg = mc.receive();

For asynchronous delivery, we can register a MessageListener object with a message consumer:

mc.setMessageListener(new MessageListener() {
    public void onMessage(Message msg) {
        ...
    }
});
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • @Evgeniy In AUTO_ACKNOWLEDGEMENT mode(non-transactional) If a failure occurs while executing the receive()[synchronous] method or the onMessage()[aysnc] method, the message is automatically redelivered ? Link : http://stackoverflow.com/questions/18712399/auto-acknowledgement-modenon-transactional-receive-vs-onmessage – lowLatency Sep 10 '13 at 06:56
11

from the docs:

For synchronous receipt, a client can request the next message from a message consumer using one of its receive methods.

For asynchronous delivery, a client can register a MessageListener object with a message consumer.

wrm
  • 1,898
  • 13
  • 24
4

One major difference as per my knowledge not stated in others answers is that MessageConsumer can make use of MessageSelectors and hence has capability to consume messages that it's interested in, where as MessageListener will listen to all messages.

From the J2EE tutorial doc http://docs.oracle.com/javaee/5/tutorial/doc/bnceh.html

JMS Message Selectors
If your messaging application needs to filter the messages it receives, you can use a JMS API message selector, which allows a message consumer to specify the messages it is interested in. Message selectors assign the work of filtering messages to the JMS provider rather than to the application.

mtk
  • 13,221
  • 16
  • 72
  • 112