Receiving a message

 

Messages are received using a QueueReceiver. This is created from a Session by using the createReceiver() method. This method takes a Queue parameter that defines from where the messages are received. See Sending a message for details of how to create a Queue object.

The sample program creates a receiver and reads back the test message with the following code:

QueueReceiver queueReceiver = session.createReceiver(ioQueue);
Message inMessage = queueReceiver.receive(1000);

The parameter in the receive call is a timeout in milliseconds. This parameter defines how long the method should wait if there is no message available immediately. We can omit this parameter, in which case, the call blocks indefinitely. If you do not want any delay, use the receiveNoWait() method.

The receive methods return a message of the appropriate type. For example, if a TextMessage is put on a queue, when the message is received the object that is returned is an instance of TextMessage.

To extract the content from the body of the message, it is necessary to cast from the generic Message class (which is the declared return type of the receive methods) to the more specific subclass, such as TextMessage. If the received message type is not known, we can use the instanceof operator to determine which type it is. It is good practice always to test the message class before casting, so that unexpected errors can be handled gracefully.

The following code illustrates the use of instanceof, and extraction of the content from a TextMessage:

if (inMessage instanceof TextMessage) {
  String replyString = ((TextMessage) inMessage).getText();
  .
  .
  .
} else {
  // Print error message if Message was not a TextMessage.
  System.out.println("Reply message was not a TextMessage");
}

If an application sends a message within a transaction, the message is not delivered to its destination until the transaction is committed. This means that an application cannot send a message and receive a reply to the message within the same transaction.


uj24450_