Weird behavior when counting messages on JMS queue

activemq-classic, java, jms, message-queue

Solution

There is a bug in ActiveMQ that is preventing the browse from returning the actual number of messages. In this case the browse is only returning a single page of messages, which is set by the maxPageSize property and documented here: http://activemq.apache.org/per-destination-policies.html

ActiveMQ currently has a bug report on this issue and it is being tracked here: https://issues.apache.org/jira/browse/AMQ-4181. This issue has been resolved and is currently scheduled to be fixed in ActiveMQ 5.8.0.

Problem

I am using Active MQ and the Java JMS. I want to count the number of messages on the queue. One approach is counting the messeages with a browser: ``` Queue queue = (Queue) session.createQueue(subject); QueueBrowser queueBrowser = session.createBrowser(queue); Enumeration<?> e = queueBrowser.getEnumeration(); int numMsgs = 0; // count number of messages while (e.hasMoreElements()) { // Message m = (Message) e.nextElement(); e.nextElement(); numMsgs++; } ``` But for a queue with 5000 pending requests, this only return 500. Another approach is this (iterate all the messeages in the queue): ``` Message message= consumer.receive(500); while(message!= null) { if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; // BytesMessage Byte System.out.println("Received message '"+ textMessage.getText() + "'"); } if(message!=null) Messages_list.add(message); message = consumer.receive(1); } ``` But this also dont give the right amount of messages pending. How can i confidently iterate akk the messages waiting in the queue?

Original source