J2EE Messaging
883
catch(JMSException jmse)
{
jmse.printStackTrace();
}
}
/**
* Receives messages until sender sends a 'q' or 'Q'
*/
public static void main(String[] args) throws Exception
{
// Create a Subscriber.
Subscriber subscriber = new Subscriber();
System.out.println("Subscriber waiting for messages(Publish 'q' OR 'Q' to
quit).");
synchronized(subscriber)
{
// Wait until the onMessage method changes the value of quit
while (!subscriber.quit)
{
try
{
// Wait until notified
subscriber.wait();
}
catch (InterruptedException ie)
{}
}
}
// Close up the JMS connections
subscriber.close();
}
}
Message receipt with the onMessage() method is asynchronous. It is also possible for the client to
receive messages synchronously. If the client wishes to receive messages synchronously it can use the
receive() method. There are three signatures for the receive() method:
q
The receive() method fetches the next message sent to the client's topic. This version of the
method won't return until a message is received. When it does return, it returns a message of
type Message.
q
The receive(long timeout) waits for a given amount of time for a message. The timeout
parameter specifies the maximum length of time the method should wait to receive a message
before it returns. If it receives no message in the specified amount of time, it will return null.
q
The receiveNoWait() method is like the receive() method, except it will return instantly
from the call, whether or not there is a waiting message. It will return either a message or
null if there is no waiting message.