Tuesday, July 26, 2011

Queue interchanges first and second element when use poll with browser

The issue I faced is, when i used QueueBrowser with  poll, Browser browsed elements in order but consumer started to remove from 2nd element. My scenario was simple,
First browser, then poll..

Our common Message Store implementation is written in a way to support all JMS providers ande code works fine with the most of the JMS providers(Qpid,ActiveMQ 5.3.XX) but didn't work with ActiveMQ 5.4.2/5.5 version..


public void peek() throws Exception {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost"); Connection connection = connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = (ActiveMQDestination) session.createQueue("TEST.FOO");
QueueBrowser browser = session.createBrowser((Queue) destination);

Enumeration enumeration = browser.getEnumeration();

if (enumeration.hasMoreElements()) {
Object msg = enumeration.nextElement();
TextMessage m = (TextMessage) msg;
System.out.println("Browsed msg " + m.getText());

}

browser.close();
session.close();
connection.close();

}

public void poll() throws Exception {

ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory( "vm://localhost");
Connection connection = connectionFactory.createConnection();
connection.start();

Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = (ActiveMQDestination) session.createQueue("TEST.FOO");

MessageConsumer consumer = session.createConsumer(destination);

TextMessage m = (TextMessage) consumer.receive(1000);
if (m != null) {
System.out.println(" Polled Messg" + m.getText());
}

consumer.close();
session.close();
connection.close();
}


I tested with above test code and it works fine with ActiveMQ V5.4.2..Not only works in the application..
To overcome the issue, we did an extra iteration wherever we use the Queuebrowser and it solved the issue..


@ the peek() call we added iteration,


  if (enumeration.hasMoreElements()) {
   Object msg = enumeration.nextElement();
   TextMessage m = (TextMessage) msg;
             while(enumeration.hasMoreElements()){
                           enumeration.nextElement();
                        }

  }

No comments:

Post a Comment