For our application which is making use of queues to achieve aynchronious processing we also have build a web-application as kind of dashboard for the system. With this web-application the system administrator can stop, start and schedule batch processes. One thing that was really handy to show on the webpage were the number of messages that are in the queue. We have defined a JMS queue in JBoss with JBoss messaging (see this post). Now to get the number of messages in the queue there were two possibilities:

  1. create a queueBrowser and browse to all messages and count them.
  2. access the queue MBean and get the attribute messageCount.

It should be no surprise that I decided to go for the second solution. Here is the (rather simple) code I used to obtain a the MBean and get the property. Remind that this code will only work if it is deployed at the same JBoss instance as were the queue's MBean is configured!

JAVA:
  1. public int getMessageCountConsumer() {
  2.       int messageCount = -1;
  3.       try {
  4.          MBeanServer server = org.jboss.mx.util.MBeanServerLocator.locateJBoss();
  5.  
  6.          // Get the MBeanInfo for the JNDIView MBean
  7.          Hashtable props = new Hashtable();
  8.          props.put("service", "Queue");
  9.          props.put("name", "MyQueue");
  10.          ObjectName name = new ObjectName("jboss.messaging.destination", props);
  11.  
  12.          messageCount = (Integer)(server.getAttribute(name, "MessageCount"));
  13.  
  14.       } catch (Exception e) {
  15.          // Error is logged but process is not broken. Not that big problem.
  16.          LOG.error("Error while getting messageCount:", e);
  17.       }
  18.       return messageCount;
  19.    }