4
votes

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?

2
Very weird behaviour, I've always had good experience with QueueBrowser. Silly questions but still - are you sure you are looking into right queue? How did you determine that there are 5000 messages? Imqadmin that's shipped with Glassfish often doesn't have up-to-date info about nr of messages, for example. - Miljen Mikic

2 Answers

7
votes

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.

1
votes

Since you are using ActiveMQ, you can make use of ActiveMQ's StatisticsPlugin: http://activemq.apache.org/statisticsplugin.html

Similarly, to query the statistics for a destination just send a message to the destination name prepended with ActiveMQ.Statistics.Destination. For example, to retrieve the statistics for a queue whose name is TEST.FOO, send an empty message to the queue named ActiveMQ.Statistics.Destination.TEST.FOO

Specifically, you might be interested in enqueueCount. I'm omitting example code here, since the example code on the plugin's webpage are concise and good.