Mustafa Çil
Mustafa Çil

Reputation: 776

Asynchronously Messaging in JMS

I have a question about JMS. I read the related questions and answers but I could not find a clear answer.

I have a basic producer like this:

public class AsyncProducer {

public static void main(String[] args) throws Exception {

    InitialContext initialContext = new InitialContext();
    Queue queue = (Queue) initialContext.lookup("queue/asyncQueue");

    try (
        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
        JMSContext jmsContext = cf.createContext();
        ){

        JMSProducer producer = jmsContext.createProducer();
        producer.send(queue, "Async Message");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

  }

}

This is my MessageListener:

public class AsyncConsumerListener implements MessageListener {

   @Override
   public void onMessage(Message message) {
      try {
         TextMessage text = (TextMessage) message;
         System.out.println("Consumer: message received: " + text.getText());
      } catch (JMSException e) {
         e.printStackTrace();
      }
   }
}

And this is my consumer:

public class AsyncConsumer {

public static void main(String[] args) throws Exception{

    InitialContext initialContext = new InitialContext();
    Queue queue = (Queue) initialContext.lookup("queue/asyncQueue");

    try (
        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
        JMSContext jmsContext = cf.createContext();
        ){

        JMSConsumer consumer = jmsContext.createConsumer(queue);

        consumer.setMessageListener(new AsyncConsumerListener());

        //Thread.sleep(10000);  

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

  }

}

First I run the Producer class and send a message to the queue. Then, when I run the Consumer class. If Thread.sleep(10000); line is commented out then the Consumer doesn't receive the message. But when I debug the Consumer it receives the message.

I know that when a message comes the listener is called in a separate thread. In this example there is a message in the queue, but the consumer doesn't receive the message unless Thread.sleep(10000) is run.

Why does my Consumer not receive the message when the Thread.sleep(10000); line is commented out?

Upvotes: 1

Views: 1003

Answers (1)

Justin Bertram
Justin Bertram

Reputation: 34973

The consumer won't receive the message without the Thread.sleep(10000) because the program will exit before the broker dispatches the message to it. This is the nature of asynchronous (i.e. non-blocking) message consumers. If you don't have something to keep your main method from exiting then it will simply reach the end and terminate.

Upvotes: 2

Related Questions