Receiving Messages Synchronously or Asynchronously

Message consumers can receive messages from destinations using one of the following modes:

  • Synchronous—A message consumer must call a receive method to explicitly fetch a message from a destination.
  • Asynchronous —A message listener is registered with a message consumer. When messages arrive for the message consumer, they are delivered by calling the listener’s onMessage() method.

Synchronous

To receive messages synchronously, call one of the following receive methods from the MessageConsumer class:

  • receive()

    Receive the next message; block indefinitely.

  • receive(long timeout)

    Receive the next message that arrives within a specified timeout interval.

  • receiveNoWait()

    Receive the next message if one is immediately available, but do not wait when there is no message available. That is, the call immediately times out when no message is available.

The following sample code shows how to receive messages synchronously:

ConnectionFactory cf = (ConnectionFactory)context.lookup("cf/default");
Topic topic = (Topic)context.lookup("topic/testDest");
connection = cf.createConnection();
 
// Create session, non-transacted and auto-acknowledge
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
// Create durable subscriber
String subscriptionName = new String("subscription");
subscriber = session.createDurableSubscriber(topic, subscriptionName);
 
connection.start();
 
// Blocking call to receive, timeout 1 second
Message testMessage = subscriber.receive(1000);
if(testMessage != null) {
// process message
}
 
connection.stop();

Asynchronous

To receive messages asynchronously, you can register a MessageListener with a MessageConsumer.

The following sample code shows how to receive messages asynchronously:

ConnectionFactory cf = (ConnectionFactory)context.lookup("cf/default");
Topic topic = (Topic)context.lookup("topic/testDest");
connection = cf.createConnection();
 
// Create session, non-transacted and auto-acknowledge
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
// Create durable subscriber
String subscriptionName = new String("subscription");
subscriber = session.createDurableSubscriber(topic, subscriptionName);
jmsMessageListener myListener = new jmsMessageListener();
subscriber.setMessageListener(myListener)
 
connection.start();
 
// Sleep for 10 seconds
Thread.sleep(10000);
 
connection.stop();
public class jmsMessageListener implements MessageListener {
public void onMessage(Message message) 
{
            // process message
}