Sun Java System Message Queue 4.3 Developer's Guide for Java Clients

Receiving Messages Asynchronously

If you want your message consumer to receive incoming messages asynchronously, you must create a message listener to process the messages. This is a Java object that implements the JMS MessageListener interface. The procedure is as follows:

ProcedureTo Set Up a Message Queue Java Client to Receive Messages Asynchronously

  1. Define a message listener class implementing the MessageListener interface.

    The interface consists of the single method onMessage, which accepts a message as a parameter and processes it in whatever way is appropriate for your application:

    public class MyMessageListener implements MessageListener
            public void onMessage (Message  inMsg)
            /* Code here to process message */
  2. Create a message consumer.

    You can use either the createConsumer or createDurableSubscriber method of the session in which the consumer will operate: for instance,

    MessageConsumer  myConsumer = mySession.createConsumer(myDest);
  3. Create an instance of your message listener class.

    MyMessageListener  myListener = new MyMessageListener();
  4. Associate the message listener with your message consumer.

    The message consumer method setMessageListener accepts a message listener object and associates it with the given consumer:

  5. Start the connection to which this consumer’s session belongs.

    The connection’s start method begins the flow of messages from the message broker to your message consumer:


    Once the connection is started, the Message Queue client runtime will call your message listener’s onMessage method each time it has a message to deliver to this consumer.

    To ensure that no messages are lost before your consumer is ready to receive them, it is important not to start the connection until after you have created the message listener and associated it with the consumer. If the connection is already started, you should stop it before creating an asynchronous consumer, then start it again when the consumer is ready to begin processing.

    Setting a consumer’s message listener to null removes any message listener previously associated with it:


    The consumer’s getMessageListener method returns its current message listener (or null if there is none):

    MyMessageListener  myListener = myConsumer.getMessageListener();