Java – the difference between a MessageListener and a Consumer in JMS

javajmsmessaging

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?

Best Answer

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) {
        ...
    }
});