N3Xg3N
N3Xg3N

Reputation: 97

MQQueueConnection.start does not continuously listen for new messages

Hi i am trying to setup a listener for MQ queue , which needs to listen to a queue continuously and deliver any new message through onMessage function. Program should not exit . Following is a snippet of my program. On MQQueueConnection.start , i get a hit in onMessage function, but after consuming 1 message from MQ, the program stops. i want the program to be running for ever and deliver new messages in the queue through onMessage function. Any ideas what i am doing wrong? With spring jms classes it works as required, though i dont want to use spring here .

public class MyListener implements MessageListener { 

    @Override
    public void onMessage(Message message)
    {
       try
       {
            handleMessage(message,session);
        }
       catch (Exception exx)
       {
            onHandleMessageException(message, exx);
        }
    }
}

public class TestListener
{
   public static void main(String[] args) {
      MyListener myListener = new MyListener();
      MQQueueConnectionFactory connFactory = new MQQueueConnectionFactory();
      //MyApplicationContext - custom class for loading MQ params
      MyApplicationContext obj=MyApplicationContext.getInstance();

      connFactory.setHostName(obj.getHost());
      connFactory.setPort(obj.getPort());
      connFactory.setQueueManager(obj.getQueueManagerName());
      connFactory.setChannel(obj.getChannel());
      connFactory.setTransportType(obj.getTransportType());

      MQQueueConnection connection=(MQQueueConnection) connFactory.createQueueConnection(obj.getMqUser(), obj.getMqPWD()) ;
      MQQueueSession session=(MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

      MQQueue queue = (MQQueue) session.createQueue("TEST.QUEUE");
      MQQueueReceiver qReceiver = (MQQueueReceiver) session.createReceiver(queue);
      qReceiver.setMessageListener(myListener);

      // expect to start a new thread, which will constantly listen for new messages 
      //on the queue and deliver it in onMessage function.
      //instead after receiving one message in onMessage, program exits
      connection.start(); 
   }
}

Upvotes: 0

Views: 1161

Answers (1)

Ton Bosma
Ton Bosma

Reputation: 181

connection.start() starts a new thread, but that thread is probably a daemon thread, so it ends when the program ends. You are lucky that you receive even 1 message.

Try for example a Thread.sleep( 60000) at the end of your main, the listener will then stay in the air for one minute and you will proabably receive a few more messages.

Upvotes: 1

Related Questions