Chapter 23
882
In this example, the Subscriber uses its onMessage(Message message) method to receive
messages. The onMessage() method is called by the broker when a message arrives at MyJMSTopic.
The message parameter contains the message that is sent to the destination that the client is listening on
(MyJMSTopic, in this case). Within the onMessage() method, the client executes functions and
performs business logic based on the contents of the message.
Before the client can view the message contents, it must cast the message to one of the five message
types discussed in the "Message Body" section of this chapter. The client can call other methods from
within the onMessage() method to help process the message:
public void onMessage(Message msg)
{
try {
String text;
First it checks to see whether the message is of type TextMessage. If it is, the client extracts the text of
the message. If it is not of type TextMessage the client converts the Message object to a String with
the toString() function. Next, it prints out the text of the message:
if(msg instanceof TextMessage)
{
// If the message is a text message, extract the text
text = ((TextMessage)msg).getText();
}
else
{
// If the message is not a text message, convert the message to a string
text = msg.toString();
}
System.out.println("Message Received: "+ text);
Finally, it checks to see if the message text is a single q or Q character, in which case it changes the value
of the quit variable to true, indicating that the main function should stop its loop:
// If the message is a single q then quit
if(text.equalsIgnoreCase("q"))
{
Both the main() and the onMessage() methods access the synchronizing variable, quit. Since these
two methods are in separate threads we must control their access to the synchronizing variable with the
synchronized keyword:
synchronized(this)
{
// Set quit to true to let main() know we are done
quit = true;
// Notify main thread to stop waiting
this.notifyAll();
}
}
}