Receiving messages

You can receive messages either synchronously or asynchronously. To receive messages synchronously (get all the messages at one time), call the receive method for the message consumer. The following code samples illustrate how to receive all the messages from a queue, using three different timeout options:

// Get all the messages from the queue. If none exists, wait until a message
// arrives.

javax.jms.TextMessage queueTextMsg = (javax.jms.TextMessage)    receiver.receive();

// Get all the messages from the queue. If none exists, wait 5000 milliseconds
//(5 seconds) or until a message arrives, whichever comes first.

javax.jms.TextMessage queueTextMsg =
   (javax.jms.TextMessage) receiver.receive(5000);

// Get all the messages from the queue. If none exists, return NULL.

javax.jms.TextMessage queueTextMsg =
   (javax.jms.TextMessage) receiver.receiveNoWait();

To receive messages asynchronously (as they are delivered), implement a message listener and install it on the message consumer, either a topic or a queue. See “Implementing and installing message listeners”.