background image

Consume System Resources

<< Creates a Connection and a Session | Starting the JMS Provider >>
<< Creates a Connection and a Session | Starting the JMS Provider >>

Consume System Resources

5. Starts the connection, causing message delivery to begin:
connection.start();
6. Receives the messages sent to the destination until the end-of-message-stream control
message is received:
while (true) {
Message m = consumer.receive(1);
if (m != null) {
if (m instanceof TextMessage) {
message = (TextMessage) m;
System.out.println(
"Reading message: " + message.getText());
} else {
break;
}
}
}
Because the control message is not a TextMessage, the receiving program terminates the
while
loop and stops receiving messages after the control message arrives.
7. Closes the connection in a finally block, automatically closing the session and
MessageConsumer
.
The receive method can be used in several ways to perform a synchronous receive. If you
specify no arguments or an argument of 0, the method blocks indefinitely until a message
arrives:
Message m = consumer.receive();
Message m = consumer.receive(0);
For a simple client program, this may not matter. But if you do not want your program to
consume system resources unnecessarily, use a timed synchronous receive. Do one of the
following:
Call the receive method with a timeout argument greater than 0:
Message m = consumer.receive(1); // 1 millisecond
Call the receiveNoWait method, which receives a message only if one is available:
Message m = consumer.receiveNoWait();
The SynchConsumer program uses an indefinite while loop to receive messages, calling receive
with a timeout argument. Calling receiveNoWait would have the same effect.
Writing Simple JMS Client Applications
The Java EE 5 Tutorial · September 2007
914