How does a client accommodate asynchronous message notifications from the JMS server?

Jerry Smith

To receive messages asynchronously, a client must:

  • Implement javax.jms.MessageListener:
    public interface MessageListener {
      void onMessage(Message message);
  • Register the message handler using setMessageListener():
      subscriber = session.createSubscriber(topic);
      SubscriberMessageThread smt = new SubscriberMessageThread(this);
      con.start(); // start connection

The use of a listener for method notifications is similar to using listeners for event notification with graphical AWT clients. Note, however, that every AWT application has a screen-updater thread running in the background that keeps the application alive when main() completes its thread of execution. Certainly, JMS clients vary enormously in function but, in general, some thread of execution must be responsible for managing the wait cycle associated with potential onMessage() invocations.

Again, clients vary in many ways, but one strategy is to design either a general-purpose class to handle this task, which can be specialized for each message-receiving scenario, or build this functionality into the client itself (the client implements MessageListener). In the first case, you could design a simple class that extends Thread and implements MessageListener, for example, MessageThread:

public class MessageThread extends Thread
    implements MessageListener {

  private String statusMessage = "";
  private boolean quit = false;

  public MessageThread() {

  public void run() {
    synchronized (this) {
      while (!quit) {
        try { wait(); }
        catch (InterruptedException ie) { }

  public void shutdown() {

  public void onMessage(Message msg) {

  public String getStatusMessage() {
    return statusMessage;

  private void setStatusMessage(String msg) {
    statusMessage = msg;

  private void notifyQuit() {
    synchronized (this) {
      quit = true;

Note that onMessage() is empty. Hence, for each message-receiving scenario, you could specialize this class providing the appropriate functionality for onMessage. (See, for example, the reference to SubscriberMessageThread in the previous code segment from the JMS client that registers the message handler.)

Note that some JMS implementations provide convenience functionality for handling the wait process, for example, ThreadHelper.WAIT_UNTIL_EXIT.suspend(), in iBus//MessageServer.

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.